9

I want to log all prepared sql statements in my java application. I'm using the standard postgres jdbc driver org.postgresql.Driver. This driver has a parameter called " loglevel" which can be set to 1 (INFO) or 2 (DEBUG). The point is if the parameter is set to 1 it's almost logging nothing, if set to 2 it's tracing too much like

...
20:59:05.608 (2)  FE=> Bind(stmt=null,portal=null,$1=<'5'>,$2=<'13'>)
20:59:05.609 (2)  FE=> Describe(portal=null)
20:59:05.609 (2)  FE=> Execute(portal=null,limit=1)  
20:59:05.609 (2)  FE=> Sync
20:59:05.648 (2)  <=BE ParseComplete [null]
20:59:05.649 (2)  <=BE BindComplete [null]
20:59:05.649 (2)  <=BE NoData
20:59:05.649 (2)  <=BE CommandStatus(UPDATE 1)
...

Is there a way to only log the statements + parameters?

1 Answer 1

10

You're lucky that you're using PostgreSQL. The PreparedStatement implementation of the PostgreSQL JDBC driver (at least, since 8.x or something) has its toString() overridden that way so you could see the entire SQL statement with all parameters filled in the right places. So you could just do something like:

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, value1);
preparedStatement.setString(2, value2);
// ...
logger.debug(preparedStatement); // Will show entire SQL with all values.

(where logger is just your logger, e.g. slf4j/logback or something)

Sign up to request clarification or add additional context in comments.

3 Comments

I'm not seeing this in the 9.1 version of the driver.
Works for me with 9.3.
If you have access to the application code, yes. Any idea how to log the statement for third-party code that you cannot change (but configure logging)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.