About Me

My photo
Ernakulam, Kerala, India
I am Sajadh, author of this blog. I run this with loads of passion.
If you are into java, you may find lot of interesting things around ...
Advance thanks for your queries to sajadhaja90@gmail.com.

Wednesday, 27 March 2013

Log4j



@Author: Mohammed Sajadh NA
@Dated : 27 Mar 2013
@Version : V1.0

·         Log4j is a Reliable, Fast and Flexible Logging Framework (APIs) written in Java.
·         Log4j has three main components:
1)      loggers: Responsible for capturing logging information.
2)      appenders : Responsible for publishing logging information to various preferred destinations.
3)      layouts: Responsible to format logging information in different styles.

log4j Features:
  • log4j is thread-safe.
  • log4j is optimized for speed.
  • log4j is based on a named logger hierarchy.
  • log4j supports multiple output appenders per logger.
  • log4j supports internationalization.
  • log4j is not restricted to a predefined set of facilities.
  • Logging behavior can be set at runtime using a configuration file.
  • log4j is designed to handle Java Exceptions from the start.
  • log4j uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
  • The format of the log output can be easily changed by extending the Layout class.
  • The target of the log output as well as the writing strategy can be altered by implementations of the Appender interface.
  • log4j is fail-stop. However, altough it certainly strives to ensure delivery, log4j does not guarantee that each log statement will be delivered to its destination.

log4j – Installation
step 1 :- Download apache-log4j-x.x.x.tar.gz from  http://logging.apache.org/log4j/.
step 2 :-
to be continued (on preparing ..... )


log4j - Architecture
Log4j API has been designed in layered where each layer provides different object which performs different tasks
There are two type of objects available with Log4j framework.
  • Core Objects: These are mandatory objects of the framework and required to use the framework.
  • Support Objects: These are optional objects of the framework and support core objects to perform addition but important tasks.
Core Objects:
A.    Logger object [Capture log info]:- 
a.       The top level layer is Logger which provides Logger object.
b.      Responsible for capturing logging information and they are stored in a namespace hierarchy
B.   Layout object [Formatting log content] :-
a.       Used to format logging information in different styles
C.   Appender object [Publishing log info]
a.       This is lower level layer which provides Appender object
b.     Responsible for publishing logging information to various preferred destinations such as a database, file, console, UNIX Syslog etc.
Support Objects:
A.   Level object :-
a.       The Level object defines the granularity and priority of any logging information
b.      There are seven levels of logging defined within the API: OFF, DEBUG, INFO, ERROR, WARN, FATAL, and ALL.
B.   Filter object :-
a.       used to analyze logging information and make further decisions on whether that information should be logged or not.
C.   Object Rendered :-
a.        The ObjectRenderer object is specialized in providing a String representation of different objects passed to the logging framework.
b.      This object is used by Layout objects to prepare the final logging information.
D.   Log Manager :-
a.       The LogManager object manages the logging framework.
b.      It is responsible for reading the initial configuration parameters from a system-wide configuration file or a configuration class.

                  

log4j – Configuration
The log4j.properties file is a log4j configuration file which keeps properties in key-value pairs. By default, the LogManager looks for a file named log4j.properties in the CLASSPATH.
Steps:-
1)       Defined level [ALL,DEBUG,INFO,WARN,..] of the root logger and attaches appender[FILE,CONSOLE,..] name to it.
2)       Set the appender name to be a valid appender [FileAppender,ConsoleAppender,..].
3)       Set the layout for the appender .

log4j.properties Syntax:
Following is the syntax of log4j.properties file for an appender X:
# Define the root logger with appender X
log4j.rootLogger  = DEBUG, X            -----------------------------à STEP 1

# Set the appender named X to be a File appender 
log4j.appender.X  = org.apache.log4j.FileAppender -------------------à STEP 2

# Define the layout for X appender
log4j.appender.X.layout = org.apache.log4j.PatternLayout ------------à STEP 3
log4j.appender.X.layout.conversionPattern = %m%n

log4j.properties Example:
# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE    // level of the root logger defined as DEBUG & attaches appender named FILE to it

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender // appender FILE is defined as org.apache.log4j.FileAppender log4j.appender.FILE.File=${log}/log.out           // writes to a file named "log.out" located in the log directory

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout //layout pattern defined is %m%n, means the printed
log4j.appender.FILE.layout.conversionPattern=%m%n         // logging will be followed by a newline character

Different Types of LEVELS, APPENDERS, LAYOUTS
LEVELS :-
ALL
All levels including custom levels.
DEBUG
Designates fine-grained informational events that are most useful to debug an application.
INFO
Designates informational messages that highlight the progress of the application at coarse-grained level.
WARN
Designates potentially harmful situations.
ERROR
Designates error events that might still allow the application to continue running.
FATAL
Designates very severe error events that will presumably lead the application to abort.
OFF
The highest possible rank and is intended to turn off logging.
TRACE
Designates finer-grained informational events than the DEBUG.


Note: A log request of level Lr  in a logger with level Lc, is enabled if Lr >= Lc.
Where Lr=  requested log
                             Lc= log set in configuration file as root logger
ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF.

See Example 1.1 in Examples
APPENDERS :-
  • AppenderSkeleton
  • AsyncAppender
  • ConsoleAppender
  • DailyRollingFileAppender
  • ExternallyRolledFileAppender
  • FileAppender
  • JDBCAppender
  • JMSAppender
  • LF5Appender
  • NTEventLogAppender
  • NullAppender
  • RollingFileAppender
  • SMTPAppender
  • SocketAppender
  • SocketHubAppender
  • SyslogAppender
  • TelnetAppender
  • WriterAppender
Each Appender object has different properties associated with it, and these properties indicate the behavior of that object.
Property
Description
layout
Appender uses the Layout objects and the conversion pattern associated with them to format the logging information.
target
The target may be a console, a file, or another item depending on the appender.
level
The level is required to control the filteration of the log messages.
threshold
Appender can have a threshold level associated with it independent of the logger level. The Appender ignores any logging messages that have a level lower than the threshold level.
filter
The Filter objects can analyze logging information beyond level matching and decide whether logging requests should be handled by a particular Appender or ignored.

LAYOUT :-
  • DateLayout
  • HTMLLayout
  • PatternLayout
  • SimpleLayout
  • XMLLayout
Using HTMLLayout and XMLLayout you can generate log in HTML and in XML format as well.

log4j - Sample Program
Following is a simple configuration file created for our example. Let me re-iterate it once again:
  • The level of the root logger is defined as DEBUG and attaches appender named FILE to it.
  • The appender FILE is defined as org.apache.log4j.FileAppender and writes to a file named "log.out" located in the log directory.
  • The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character.

log4j.properties
# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE
 
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
 
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
 
 
web.xml
<servlet>
      <servlet-name>eteam-log4j-init</servlet-name>
      <servlet-class>com.sajadhaja.LoggerEvent</servlet-class>
      <init-param>
            <param-name>log4j-property-file</param-name>
            <param-value>WEB-INF/classes/log4j.properties</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
</servlet>
com.sajadhaja.LoggerEvent
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.PropertyConfigurator;

public class LoggerEvent extends HttpServlet
{

 public LoggerEvent (){}

 public void init() throws ServletException
  {  
   String strPropertyFile = getInitParameter("log4j-property-file");
   if(strPropertyFile != null)
   PropertyConfigurator.configure((new   StringBuilder(String.valueOf(getServletContext().getRealPath("/")))).append(strPropertyFile).toString());
  }

    private static final long serialVersionUID = 1L;
}
log4j in Java Program
import org.apache.log4j.Logger;
 
import java.io.*;
import java.sql.SQLException;
import java.util.*;
 
public class log4jExample{
  /* Get actual class name to be printed on */
  static Logger log = Logger.getLogger(
                      log4jExample.class.getName());
 
  public static void main(String[] args)
                throws IOException,SQLException{
   
     log.debug("Hello this is an debug message");
     log.info("Hello this is an info message");
  }
}

No comments:

Post a Comment

You can enter queries here...