Log4j API – Sample Programs


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 static void main(String a[])
{
Logger l=Logger.getLogger(Example1.class);
Layout lay=new SimpleLayout();
ConsoleAppender ap=new ConsoleAppender(lay);

l.addAppender(ap);
l.setLevel(Level.DEBUG);

try{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
l.debug(“driver loaded”);
Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@192.168.1.214:1521:XE”,”kiran”,”kiran”);
l.info(“connection established successfully”);

}catch(ClassNotFoundException e)
{
l.fatal(” OOPS………DriverClass Problem(plz check Driverclass)”);
e.printStackTrace();
}catch(SQLException se)
{
l.fatal(“OOPS…………Db Connection Problem”);
se.printStackTrace();
}
catch(Exception se)
{
l.error(“OOPS…………Db Problem”);
se.printStackTrace();
}

}
}

 

File Appender example in Log4j :

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

import org.apache.log4j.*;

//FileAppender

public class Example2  {

public static void main(String a[])
{
Logger l=Logger.getLogger(Example2.class);
try{
Layout lay=new SimpleLayout();
FileAppender ap=new FileAppender(lay,”sample.log”,true);
l.addAppender(ap);
l.setLevel(Level.DEBUG);
}catch(Exception d)
{
l.debug(“log4j stmts problem”);
}
try{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
l.debug(“driver loaded……”);
Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@192.168.1.214:1521:XE”,”kiran”,”kiran”);
l.info(“connection established successfully……….”);

}catch(Exception e)
{
l.fatal(“Db Problem”);
e.printStackTrace();
}
}
}

Log4j


→ Log4j has three main components: loggers, appenders and layouts. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.

→ Loggers are named entities. Logger names are case-sensitive and they follow the hierarchical naming rule:

Named Hierarchy :

A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of the descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors between itself and the descendant logger.

→ For example, the logger named “com.foo” is a parent of the logger named “com.foo.Bar”. Similarly, “java” is a parent of “java.util” and an ancestor of “java.util.Vector”. This naming scheme should be familiar to most developers.
The root logger resides at the top of the logger hierarchy. It is exceptional in two ways:
1.it always exists,
2.it cannot be retrieved by name.

Invoking the class static Logger.getRootLogger method retrieves it. All other loggers are instantiated and retrieved with the class static Logger.getLogger method. This method takes the name of the desired logger as a parameter. Some of the basic methods in the Logger class are listed below.

package org.apache.log4j;

public class Logger {

// Creation & retrieval methods:
public static Logger getRootLogger();
public static Logger getLogger(String name);

// printing methods:
public void trace(Object message);
public void debug(Object message);
public void info(Object message);
public void warn(Object message);
public void error(Object message);
public void fatal(Object message);

// generic printing method:
public void log(Level l, Object message);
}

Loggers may be assigned levels. The set of possible levels, that is:

TRACE,
DEBUG,
INFO,
WARN,
ERROR and
FATAL

Logging requests are made by invoking one of the printing methods of a logger instance. These printing methods are debug, info, warn, error, fatal and log.

A logging request is said to be enabled if its level is higher than or equal to the level of its logger. Otherwise, the request is said to be disabled. A logger without an assigned level will inherit one from the hierarchy. This rule is summarized below.

Basic Selection Rule
A log request of level p in a logger with (either assigned or inherited, whichever is appropriate) level q, is enabled if p >= q.

This rule is at the heart of log4j. It assumes that levels are ordered. For the standard levels, we have DEBUG < INFO < WARN < ERROR < FATAL.

Configuration of the log4j environment is typically done at application initialization. The preferred way is by reading a configuration file.