Tuesday, September 11, 2012

Log4j with NetBeans IDE

I think this post will help you to configure the log4j in Netbeans IDE

First you have to create the Java Project "Log4j"
Then you have to put the "log4j.properties" file in to your src folder "This should be located in root"

[sourcecode language="text"]
#### Use Three appenders,
#stdout - is used for write to console
#R - is used for write to file
log4j.rootLogger=debug, stdout, R
# Print only messages of priority WARN or higher for your category
# log4j.category.your.category.name=WARN
# Specifically inherit the priority level
#log4j.category.your.category.name=INHERITED

# Print only messages of level WARN or above in the package
#This is use for debuging mode
log4j.logger.testlogging=DEBUG

 

#### Appender writes to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd} %5p [%t] (%F:%L) - %m%n

 

#### Appender writes to a file
#log4j.appender.R=org.apache.log4j.FileAppender
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
# Control the maximum log file size
log4j.appender.R.MaxFileSize=100KB
# Archive log files (one backup file here)
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd} %5p [%t] (%F:%L) - %m%n
#log4j.appender.R.layout.ConversionPattern=%n%p - %m
[/sourcecode]


Finally you have to take this "log4j-1.2.17.jar" file and add in to the class path

Now you done all configuration lets try to use it

[sourcecode language="java"]
package log4j;

import org.apache.log4j.Logger;

/**
*
* @author dinuka
*/
public class Log4J {

//initializing the logger
static Logger log = Logger.getLogger(Log4J.class.getName());

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//logging in different levels
log.trace("This is a Trace");
log.debug("This is a Debug");
log.info("This is an Info");
log.warn("This is a Warn");
log.error("This is an Error");
log.fatal("This is a Fatal");

}
}
[/sourcecode]

Output file

[sourcecode language="text"]
2012-09-11 TRACE [main] (Log4J.java:19) - This is a Trace
2012-09-11 DEBUG [main] (Log4J.java:20) - This is a Debug
2012-09-11 INFO [main] (Log4J.java:21) - This is an Info
2012-09-11 WARN [main] (Log4J.java:22) - This is a Warn
2012-09-11 ERROR [main] (Log4J.java:23) - This is an Error
2012-09-11 FATAL [main] (Log4J.java:24) - This is a Fatal

[/sourcecode]

1 comment: