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?
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.
cmd.errors.allErrors.each {
log.debug it
}
Edit (More Verbose)
cmd.errors.allErrors.each {err ->
log.debug("[$err.field]: $err")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With