Last Updated on 26 September 2019   |   Print Email
In this Hibernate tutorial, I will guide you how to configure your Java project to use log4j version 2.x with Hibernate framework.By default, Hibernate uses JBoss logging API to print logging information to the standard console, something like this:Besides the default logging, Hibernate also allows programmers to plugin external logging framework if they wish to have control over the logging process. And in this post, you will learn how to use log4j2 (log4j version 2.x) with Hibernate.
1. Specify log4j2 dependency
First, you need to add log4j2’s JAR files to the project’s classpath, namely log4j2-api-2.x.x.jarand log4j2-core-2.x.x.jar. You can download log4j2 JAR files here.In case you use Maven, specify the following dependencies in the pom.xml file:
This is a simple log4j configuration that prints log information to the standard output console (Console appender). Two Hibernate log categories used are org.hibernate and org.hibernate.SQL:
You can see the complete list of Hibernate log categories here.Run the project and you will see the default log format is replaced by log4j’s:To also write log information to a file, use the following configuration:
To change the log layout pattern, refer to this tutorial.
3. Configure Hibernate logging using log4j via log4j2.properties file
In case you want to use properties file instead of XML, create the log4j2.properties file under the src/main/resources directory of your project as follows:And put the following content:
As you can see in this log4j2.properties file we use two appenders, one for console and one for file, and we specify a logger for the Hibernate log category org.hibernate.SQL that logs all SQL statements. You can see the complete list of Hibernate log categories here.NOTE: If you use the log category org.hibernate.SQL, you should set the hibernate.show_sql property to false in Hibernate configuration file.You can watch the video version below: That’s how to enable Hibernate logging using log4j2. Check the following tutorials to learn more about Hibernate framework:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments