Grails: How to log within static methods

Grails injects a log object for each artifact, but these loggers are not accessible within static methods.

Here’s a quick-and-dirty code snippet sample that demonstrates how to log from a static method within domain class Account. The trick is to get the Logger by invoking org.apache.commons.logging.LogFactory.getLog(this):

import org.apache.commons.logging.LogFactory

static Account createOrFindByImei(String imei)
    Account result = Account.findByImei(imei)
    return result ? result  :
    saved(new Account(
            name:"* New Account ($imei) created at " + new Date()))

private static Account saved(Account account)
        return account
      .error("!saved: $account.errors", new Throwable("*STACKTRACE*"))

About Reiner

Born 1954 in Ratisbon (Bavaria, Germany), in 1976 punched cards at Berlin Technical University, caught hacking one of its mainframes by Horst Zuse (son of Konrad Zuse), started studying computer science and soon was offered a job whithin their computer department doing systems programming for IBM VM/370. While studying, jobbed around Germany at various places doing all sorts of things, then returned to Berlin to work at SRZ (computer aided typesetting). Never finished my master degree, but chose to take up self-employed work (which didn't turn me rich nor famous). Now working for a mid-sized software company within a very promising department as head of server software development.
This entry was posted in Uncategorized. Bookmark the permalink.

1 Response to Grails: How to log within static methods

  1. That’s useful. Worked for me. Thanks for sharing.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s