Logging in the PostgresSQL Java driver

98 views Asked by At

I'm developing a Kotlin application that uses a PostgreSQL database via Exposed. I'm trying to debug an error and I would like to see what SQL is sent to the database. The driver docs says it uses java.util.logging. How can I configure it so that SQL appears on the console, just for debugging purposes?

I'm asking for a quick and dirty hack to aid in debugging, so I would prefer avoiding a logging configuration file and configure everything in code, if possible.

I tried the code below, but only the SQL code of the line that throws is printed, alongside with the stack trace of the exception:

val logger = Logger.getLogger("org.postgresql")
logger.level = Level.ALL
val handler = ConsoleHandler()
handler.level = Level.ALL
handler.formatter = SimpleFormatter()
logger.addHandler(handler)
    
Database.connect(
    "jdbc:postgresql://localhost:5432/money",
    driver = "org.postgresql.Driver",
    user = "***",
    password = "***"
)

MyTable.batchInsert(/*...*/) {/*...*/} // When I execute this I want the SQL to appear on the console
MyOtherTable.batchInsert(/*...*/) {/*...*/} // This is the line that throws an exception
1

There are 1 answers

2
Andrei Naumets On BEST ANSWER

You can try adding logging.

 implementation("ch.qos.logback:logback-classic:1.4.5")

And add logback.xml to your resources.

<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{100} -> %msg%n</pattern>
    </encoder>
</appender>
<root level="trace">
    <appender-ref ref="STDOUT"/>
</root>
<logger name="Exposed" level="TRACE"/>
<logger name="com.zaxxer.hikari.pool.PoolBase" level="ERROR"/>
<logger name="com.zaxxer.hikari.pool.HikariPool" level="ERROR"/>
<logger name="io.ktor.routing.Routing" level="ERROR"/>
<logger name="io.ktor.server.plugins.contentnegotiation.ContentNegotiation" level="ERROR"/>
<logger name="io.ktor.server.auth.Authentication" level="ERROR"/>
<logger name="io.ktor.server.engine.DefaultTransform" level="ERROR"/>
</configuration>

This is the code for my case.