Hibernate logging methods

Greetings, dear friends! My name is Alexey, I am a HR production developer. In this article, I propose to discuss the ways of logging Hebernate.





Hibernate is a great tool to get the job done, especially when it functions quickly and well, but when problems arise, you need to look at what's going on under the hood. Configuration examples will be provided in Spring.





The first and easiest way

Specify in application.properties: spring.jpa.show-sql=true



orspring.jpa.properties.hibernate.show_sql=true).







This approach allows you to quickly solve the problem and help in finding bugs locally. But there are two obvious disadvantages:





1. The sql output does not go through our logger and does not have a convenient format for us.





2. .





— properties,

logging.level.org.hibernate.SQL=DEBUG







logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE







, . , .





— proxy

log4jdbc p6spy. , log4jdbc .





<groupId>com.integralblue</groupId>







log4jdbc-spring-boot-starter







<groupId>com.github.gavlyukovskiy</groupId>







p6spy-spring-boot-starter







, . : , . p6spy.





- .





decorator.datasource.p6spy.log-filter.pattern=.*insert.*



insert .





. . :





In fact, we need to filter the required logs by some attribute. I decided to do this using MDC, its scope is just ThreadLocal, which suits us. Let's make a filter:





I made the annotation processor through an aspect:





Well, the configuration using the example of Logback:





Let's create an additional appender with a filter and pass the p6spy logs of the info level through it and do not forget to specify additivity = "false" so that the root appender does not process the same package. That's all. Do not forget that we did it through a proxy, which means we have limitations in the choice of methods over which we can put a new annotation.





That's all. Hope was helpful!








All Articles