Searching...
Saturday, 2 January 2016

Log4j Simple xml configuration example

20:43

1. Add below dependency in your project

<dependency>
<groupid>log4j</groupid>
<artifactid>log4j</artifactid>
<version>1.2.17</version>
</dependency>

2. Create a log4j.xml file

<log4j:configuration debug="true" xmlns:log4j="http://jakarta.apache.org/log4j/">

<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n">
</layout>
</appender>

<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
<param name="append" value="false">
<param name="file" value="mylog.log">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n">
</layout>
</appender>

<root>
<level value="INFO">
<appender-ref ref="consoleAppender">
<appender-ref ref="fileAppender">
</appender-ref></appender-ref></level></root>
</log4j:configuration>
This should place in your resource folder

3. Create a main class to test

package com.vinod.test;

import org.apache.log4j.Logger;
public class Log4jTest {
static Logger logger = Logger
.getLogger(Log4jTest.class.getName());
public static void main(String[] args) {
logger.info("Info test");
logger.debug("Debug test");
}

}

4. Ouput - mylog.log

 23:32:01,101 INFO [Log4jTest] Info test

 

0 comments: