Selective SQL logging possible?

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Selective SQL logging possible?

Göran Ehrsson
Hi,

Is it possible to enable SQL logging for just a section of code?
I just want to look at the SQL output from one method.
When I enable logging i DataSource.groovy I get thousands of lines and it's a pain to find the right spot.
Something like this would be nice when debugging:

Sql.withLogging{
    myService.myMethod()
}

Regards

/Goran Ehrsson
Reply | Threaded
Open this post in threaded view
|

Re: Selective SQL logging possible?

longwa
I haven't tried it, but maybe you can just modify the config at runtime? If so, you could create a helper like this:

def logSql(Closure c) {
    grailsApplication.config.dataSource.logSql = true
    try {
        c()
    }
    finally {
        grailsApplication.config.dataSource.logSql = false
    }
}


On Tue, Jun 19, 2012 at 5:36 PM, Göran Ehrsson <[hidden email]> wrote:
Hi,

Is it possible to enable SQL logging for just a section of code?
I just want to look at the SQL output from one method.
When I enable logging i DataSource.groovy I get thousands of lines and it's a pain to find the right spot.
Something like this would be nice when debugging:

Sql.withLogging{
    myService.myMethod()
}

Regards

/Goran Ehrsson

Reply | Threaded
Open this post in threaded view
|

Re: Selective SQL logging possible?

talldave
In reply to this post by Göran Ehrsson
try this blog post.  i think it details how to do just what you're looking for.

http://www.intelligrape.com/blog/2011/10/21/log-sql-in-grails-for-a-piece-of-code/
Reply | Threaded
Open this post in threaded view
|

Re: Selective SQL logging possible?

arcesino
You can activate/deactivate hibernate-generated queries using the following self-explanatory flags:

sessionFactory.settings.sqlStatementLogger.logToStdout = true
sessionFactory.settings.sqlStatementLogger.formatSql = true


Remember that sessionFactory is the spring bean.

Therefore, you can create a dynamic method like:

Sql.metaClass.withLogging(Closure cls) {
  def sessionFactory = Holders.applicationContext.sessionFactory
  sessionFactory.settings.sqlStatementLogger.logToStdout = true
  sessionFactory.settings.sqlStatementLogger.formatSql = true

  cls.call()

  sessionFactory.settings.sqlStatementLogger.formatSql = false
  sessionFactory.settings.sqlStatementLogger.formatSql = false
}

Hope it helps!