Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I log Grails command object errors?

What is the most effective way to log a command object with errors in Grails?

My current logging is just,

if (!cmd.validate()) log.debug("command invalid ${cmd.errors}")

but it just spews out an unreadable mess of output.

Anyone have any suggestions to improve logging of command objects?

like image 640
James McMahon Avatar asked Apr 25 '26 00:04

James McMahon


2 Answers

Add a dependency injection for the messageSource bean:

def messageSource

and then you can build a map keyed by field name with the validation errors for that field:

def locale = Locale.default
def stringsByField = [:].withDefault { [] }
for (fieldErrors in cmd.errors) {
   for (error in fieldErrors.allErrors) {
      stringsByField[error.field] << messageSource.getMessage(error, locale)
   }
}

and you can just run println stringsByField or look for individual problems by key.

Here I'm using the default Locale, but if you're using localization use the current one for the request.

like image 182
Burt Beckwith Avatar answered Apr 26 '26 14:04

Burt Beckwith


cmd.errors.allErrors.each {
    log.debug it
}

Edit (More Verbose)

cmd.errors.allErrors.each {err ->
    log.debug("[$err.field]: $err")
}
like image 28
dmahapatro Avatar answered Apr 26 '26 13:04

dmahapatro