Monday, February 23, 2015

Log4j with Maven

Log4j with Maven


1. Add dependency.

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

2. Add log4j.properties file inside "src/main/java" package (Because when we are building the project this file will reside in /target/classes, you can select any package which is a java build path source )



# Root logger option
log4j.rootLogger=DEBUG, stdout, file
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=GIVE_PATH_FOR_LOGFILE
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


3. Main function


import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;


public class LogMain {
final static Logger logger = Logger.getLogger(LogMain.class);
public static void main(String[] args) {
logger.debug("test debug");
logger.error("test error");
}
}

4. Run !!

You will get this in “GIVE_PATH_FOR_LOGFILE”

2015-02-23 15:42:39 DEBUG LogMain:12 - test debug
2015-02-23 15:42:39 ERROR LogMain:13 - test error



No comments:

Post a Comment

Total Pageviews

Translate