Skip to content

Instantly share code, notes, and snippets.

@davidkuster
Last active January 27, 2016 16:25
Show Gist options
  • Save davidkuster/87c07208bf43145f7b91 to your computer and use it in GitHub Desktop.
Save davidkuster/87c07208bf43145f7b91 to your computer and use it in GitHub Desktop.
/**
* Utility methods to make logging a little cleaner. Instead of having to put
* log.isDebugEnabled() (and etc) checks everywhere we want to log to debug, this will do the
* check in a single place. And because the strings to log are being passed as a closure, they
* will be lazily evaluated.
*
* Note: this trait assumes there is a "log" variable on the class, presumably injected into
* Grails artefacts or through use of the groovy.util.logging.Slf4j annotation.
*
* Note: updated all methods to static so these can be called from static methods. Required
* assumption now is that log var will be static as well, which it presumably should be anyway.
*
* Usage:
* logDebug { "Log this if debug is enabled, and if not avoid ${expensiveComputation()}" }
*
* Same for logTrace, logInfo, logWarn and logError. logError can optionally be called with an exception,
* and the parameter order is optional so parens can be used or not.
*
* No parens option:
* logError exception, { "Log this if error is enabled, and if not avoid ${expensiveComputation()}" }
*
* With the no parens option, param order is reversed from the typical: log.error "string to log", e
*
* Parens option:
* logError({ "Log this if error is enabled, and if not avoid ${expensiveComputation()}" }, exception)
*
* Param order is typical, but parentheses are required.
*/
trait LoggingUtil {
static void logTrace(Closure c) {
if (log.traceEnabled) {
log.trace c()
}
}
static void logDebug(Closure c) {
if (log.debugEnabled) {
log.debug c()
}
}
static void logInfo(Closure c) {
if (log.infoEnabled) {
log.info c()
}
}
static void logWarn(Closure c) {
if (log.warnEnabled) {
log.warn c()
}
}
static void logError(Closure c) {
if (log.errorEnabled) {
log.error c()
}
}
// Groovy wants closures to be the last param, so have to reverse the order from the usual
static void logError(Exception e, Closure c) {
if (log.errorEnabled) {
log.error c(), e
}
}
static void logError(Throwable t, Closure c) {
if (log.errorEnabled) {
log.error c(), t
}
}
// adding additional option so user has the choice on param order and parens usage for logError
static void logError(Closure c, Exception e) {
if (log.errorEnabled) {
log.error c(), e
}
}
static void logError(Closure c, Throwable t) {
if (log.errorEnabled) {
log.error c(), t
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment