James McMahon
James McMahon

Reputation: 49659

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?

Upvotes: 2

Views: 1495

Answers (2)

dmahapatro
dmahapatro

Reputation: 50285

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

Edit (More Verbose)

cmd.errors.allErrors.each {err ->
    log.debug("[$err.field]: $err")
}

Upvotes: 4

Burt Beckwith
Burt Beckwith

Reputation: 75681

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.

Upvotes: 7

Related Questions