Log4j API – Sample Programs

Posted: February 7, 2012 in Java Posts

Java Tutorials

Log4j Examples:

The basic example to implement the Log4j:

import org.apache.log4j.Logger;

public class LogExample {

public LogExample() {
}
static Logger log = Logger.getLogger(LogExample.class);

public static void main(String argsp[]) {

log.debug(“projectname-modulename-Class-method-Here is some DEBUG”);
log.info(“projectname-modulename-Class-method-Here is some INFO”);
log.warn(“projectname-modulename-Class-method-Here is some WARN”);
log.error(“projectname-modulename-Class-method-Here is some ERROR”);
log.fatal(“projectname-modulename-Class-method-Here is some FATAL”);
log.warn(“projectname-modulename-Class-method-Here is some WARN”);

}
}

 

The sample example to read the log4j configurations from properties file:

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

public class Example2  {

public static void main(String a[])
{
Logger l=Logger.getLogger(Example2.class);

PropertyConfigurator.configure(“src/prop.properties”);

l.setLevel(Level.DEBUG);
l.debug(“Myprojectname-modulename-Class-method-ok executedddddddddddddd”);
l.info(“projectname-modulename-Class-method-some infoooooooooo”);
l.warn(“projectname-modulename-Class-method-warn msg”);
l.error(“projectname-modulename-Class-method-error msg……”);
l.fatal(“projectname-modulename-Class-method-this is some fatal errrrrrrr”);
}
}

Log4j configurations in properties file: prop.properties

log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.stdout.File=logs/dailyrollfile3333.txt
log4j.appender.stdout.DatePattern=’.’yyyy-MM-dd-HH-mm
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%r  [%t]  %p  %c  %m  %d  %n


Implementing log4j with Console appender :

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

//ConsoleAppender
public class Example1 {

public…

View original post 109 more words

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s