Make H2 Log Via SLF4J

If you want your in-memory H2 database to log via SLF4J so you can control its logging output using your logging framework of choice, add this canonical string to your JDBC URL:

INIT=SET TRACE_LEVEL_FILE=4

The actual property you are setting in this case is the INIT property.  Here, you have set it to be equal to exactly one statement.  You can of course set it to be equal to several statements:

INIT=SET TRACE_LEVEL_FILE=4;SET DB_CLOSE_DELAY=-1;

The examples above are canonical strings, free of escape characters.  If you are setting these inside a Java String you’ll need to escape things properly.  Here’s a sample JDBC URL written as a double-quoted Java String that makes H2 log using SLF4J and runs some DDL on every connection:

"jdbc:h2:mem:chirp;INIT=SET TRACE_LEVEL_FILE=4\\;RUNSCRIPT FROM 'classpath:foo.ddl'"

Note the double backslashes: the first backslash escapes the next one, which, in turn, escapes the semicolon, because the semicolon is used as a delimiter in the actual JDBC URL itself.

The important thing in all of these cases is that SET TRACE_LEVEL_FILE=4 must come first in the INIT property value.

Author: Laird Nelson

Devoted husband and father; working on Helidon at the intersection of Java, Jakarta EE, architecture, Kubernetes and microservices at Oracle; open source guy; Hammond B3 player and Bainbridge Islander.

%d bloggers like this: