Hibernate Logging by Log4j using xml file

Logging enables the Developer to write the log details into a file permanently.Apache Log4j (if log4j.jar exists in your library classpath) and Logback frameworks can be used in hibernate framework to support logging.

There are two ways to perform logging using log4j:

  1. By log4j.xml file
  2. By log4j.properties file

Steps to perform Hibernate Logging by Log4j using xml file

There are two ways to perform logging using log4j using xml file:

  1. Load the log4j jar files with hibernate
  2. Create the log4j.xml file inside the src folder (parallel with hibernate.cfg.xml file)

Example of Hibernate Logging by Log4j using xml file

You can enable logging in hibernate by following only two steps in any hibernate example. This is the first example of hibernate application with logging support using log4j.

Load the required jar files

You need to load the slf4j.jar and log4j.jar files with hibernate jar files.

Create log4j.xml file

Now you need to create log4j.xml file. In this example, all the log details will be written in the C:/javatportallog.log file.

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
	debug="false">
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
 <layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{2}: %m%n" />
 </layout>
</appender>
	<appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
		<appender-ref ref="CONSOLE" />
		<appender-ref ref="FILE" />
</appender>
<appender name="FILE" class="org.apache.log4j.RollingFileAppender">
	<param name="File" value="C:/javatportallog.log" />
	<param name="MaxBackupIndex" value="100" />
 <layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{2}: %m%n" />
</layout>
</appender>
	<category name="org.hibernate">
		<priority value="DEBUG" />
	</category>
	<category name="java.sql">
		<priority value="debug" />
	</category>
	<root>
		<priority value="INFO" />
		<appender-ref ref="FILE" />
	</root>
</log4j:configuration>