Log Sql in grails for a piece of code
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.
[java]
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
}
[/java]
Now when I want to see the logs I do something like following.
[java]
String name = "Uday"
Person person
LogSql.execute {
person = Person.findByName(name)
}
[/java]
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
I improved a little bit the code. I dealt with exceptions for always return to current level
Cool, great help mate 🙂
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?
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..
Nice catch. Was looking for the same.
Thanks for sharing.