When wrestling with GORM queries you may find yourself needing to turn on SQL logging in grails. This is quite easy to setup in DataSource.groovy by setting logSql:
dataSource { // ... logSql = true }
However, I find it more convenient and safer to switch this value from the command line:
grails -DlogSql=true run-app
This is possible if you change your DataSource.groovy slightly:
dataSource { // ... logSql = Boolean.parseBoolean(System.properties.logSql ?: 'false') }
The fun doesn’t stop there. We can do a bit better (although much more verbose) by also logging result sets and parameter bindings. To set this up, we need to modify Config.groovy:
log4j = { appenders { // ... } root { // ... } // Your application specific logging configuration here ... if (Boolean.parseBoolean(System.properties.traceSql ?: 'false')) { trace 'org.hibernate.SQL', 'org.hibernate.type' } }
Now, with the flip of some swiches, our command line interface to run-app now looks like this:
grails -DlogSql=true -DtraceSql=true run-app
This will give us the essential information we need to tackle some really hardcode SQL issues. The fact that it is set on the command line ensures that we don’t accidentally check-in these values for our production settings. This is a good thing since it creates a great deal of information that can quickly fill up a hard drive.
If you want terser output, at the expensive of being more invasive, you should consider the p6spy plugin.
3 comments
Comments feed for this article
November 20, 2009 at 5:01 am
Michael Masters
Great information! I’m able to use the following command:
But when I try to use both options, I get the following
November 20, 2009 at 8:06 pm
btiernay
Sorry, you may need to reverse the order or the arguments to run-app:
grails -DlogSql=true -DtraceSql=true run-app
Also note that
traceSql
will also do whatlogSql
does, sologSql
it’s not really needed in this case.November 22, 2009 at 5:25 am
Michael Masters
Sweet! Thanks!