Log Sql in grails for a piece of code

21 / Oct / 2011 by Uday Pratap Singh 5 comments

There are time when we need to see the sql logging statement just for a method of for a particular code. Although we already have logSql property in DataSource to do it for us but it sometimes makes difficult if we need to see the log for a small piece of code rather than for whole project.
So I need something that will execute my code withing a block which automatically starts sql logging and switch it off when code is finished. Groovy closures are the solution for this problem. For doing it I created a class LogSql which have a static execute method that takes the closure as parameter.

import org.apache.log4j.Level
import org.apache.log4j.Logger

public static def execute(Closure closure) {
        Logger sqlLogger = Logger.getLogger("org.hibernate.SQL");
        Level currentLevel = sqlLogger.level
        sqlLogger.setLevel(Level.TRACE)
        def result = closure.call()
        sqlLogger.setLevel(currentLevel)
        result
}

Now when I want to see the logs I do something like following.

String name = "Uday"
Person person
LogSql.execute {
       person = Person.findByName(name)
}

This prints the sql statement for all the sql fired in the given piece of code block.

Hope it helps
Uday Pratap Singh
uday@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (5)

  1. Alberto Vilches

    Hey, nice trick!! Only one thing, if you change the global “org.hibernate.SQL” logger, you change it for every other piece of code using that. Can’t you change it only fo the current thread?

    Reply
  2. Kushal

    Nice,, good find,, i can get a lot I will make an annotation for it(with variations and enhancements) and add them To the super-Programmer Plugin annotation library..

    Reply

Leave a comment -