Insert into database using Log4j2 (JDBCAppender)
Pre-Requisite
1. Table should be already created in the database
Steps
1. Create log4j2.xml
If the deployed application is ear then place log4j2.xml inside ear directly and if the deployed application is war then place the log4j2.xml file in WEB-INF folder
Each tables mapping should be done in the log4j2.xml file
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info">
<CustomLevels>
<CustomLevel name="EMPLOYEE" intLevel="50" />
<CustomLevel name="DEPARTMENT" intLevel="51" />
</CustomLevels>
<Appenders>
<JDBC name="employeeLogAppender" tableName="EMPLOYEE">
<DataSource jndiName="java:Datasource" />
<Column name="Name" pattern="%X{Name}" isUnicode="false"/>
<Column name="empid" pattern="%X{empid}" isUnicode="false"/>
<Column name="city" pattern="%X{city}" isUnicode="false"/>
<Column name="department" pattern="%X{department}" isUnicode="false"/>
<Column name="designation" pattern="%X{designation}" isUnicode="false"/>
<Column name="experience" pattern="%X{experience}" isUnicode="false"/>
</JDBC>
<JDBC name="departmentAppender" tableName="DEPARTMENT">
<DataSource jndiName="java:Datasource" />
<Column name="name" pattern="%X{name}" isUnicode="false"/>
<Column name="deptid" pattern="%X{deptid}" isUnicode="false"/>
<Column name="total" pattern="%X{total}" isUnicode="false"/>
</JDBC>
</Appenders>
<Loggers>
<logger name="com.package.class" additivity="false">
<AppenderRef ref="departmentAppender" level="DEPARTMENT" />
</logger>
<Root level="trace" includeLocation="false" additivity="false">
<AppenderRef ref="employeeLogAppender" level="EMPLOYEE" />
</Root>
</Loggers>
</Configuration>
Here,
1. The custom logger levels have been created and each has an intlevel which is the integer value. We should not use the standard log levels which are given below and choose the appropriate intlevel. Standard Level intLevel OFF 0 FATAL 100 ERROR 200 WARN 300 INFO 400 DEBUG 500 TRACE 600 ALL Integer.MAX_VALUE
2. additivity="false" will not propagate the message to the root logger
log4j-1.2-api-X.X.jar
log4j-api-X.X.jar
log4j-core-X.X.jar
3. Add below code in the java file
//Initializee log4j2 configuration file
Configurator.initialize(null, "log4j2.xml");
//Employee table
try
{
ThreadContext.put("Name", "Sakina Shaikh");
ThreadContext.put("empid", "686");
ThreadContext.put("city", "Mumbai");
ThreadContext.put("department", "IT");
ThreadContext.put("designation", "Sr. Software Engineer");
ThreadContext.put("experience", "6");
Logger logger = LogManager.getLogger();
logger.log(Level.forName("EMPLOYEE", 50), "");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
ThreadContext.clearAll();
}
//Department table
try
{
ThreadContext.put("name", "IT");
ThreadContext.put("deptid", 1);
ThreadContext.put("total", 123);
Logger logger = LogManager.getLogger();
logger.log(Level.forName("DEPARTMENT", 51), "");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
ThreadContext.clearAll();
}
Comments
Post a Comment