Log4J Tutorial (转)

Log4J Architecture - Introduction to the Log4J architecture

Three main component of Log4J

The architecture of Log4J framework is layered and consists of three main components. There components of the Log4J are:

<script type="text/javascript">&lt;!-- google_ad_client = &quot;pub-0714075272818912&quot;; /* 120x90, created 1/11/09120x90-Link-1 */ google_ad_slot = &quot;4632423086&quot;; google_ad_width = 120; google_ad_height = 90; //--&gt; </script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script><script>google_protectAndRun(&quot;ads_core.google_render_ad&quot;, google_handleError, google_render_ad);</script>
  1. Logger
  2. Appender
  3. Layout

1. Logger

Logger is the most essential component of the logging process. It is responsible for capturing the logging information. There are 5 different log levels of the Logger. The level of Logger are as following:

There are 5 normal levels of logger:

  • DEBUG : Most useful to debug an application .
  • INFO : It provides informational messages.
  • WARN : It provides that application may have harmful events.
  • ERROR : It provides that application having error events but that might allow it to continue running.
  • FATAL : It denotes the severe error events which lead the application to abort.

  In addition, there are two special levels also they are:

  • ALL : It is intended to turn on all logging
  • OFF : It is intended to turn off logging

  You can also set the logger level by putting a simple code like

logger.setLevel((Level)Level.WARN);
 

2. Appenders in Log4J:

The Appender is responsible for publishing the log to a destination. It controls how the logging provides the output.

There are few list of appenders listed below:

  • ConsoleAppender
  • DailyRollingFileAppender
  • FileAppender
  • RollingFileAppender
  • WriterAppender
  • SMTPAppender
  • SocketAppender
  • SocketHubAppender
  • SyslogAppender sends
  • TelnetAppender

 ConsoleAppender is used as:

  ConsoleAppender appender = new ConsoleAppender(new PatternLayout());
 FileAppender

 is used as:





FileAppender appender = new FileAppender(new PatternLayout(),"filename");
 WriterAppender

 is used as:

appender = new WriterAppender(new PatternLayout(),new FileOutputStream("filename"));

3. Layouts in Log4J:

For each Appender it needs to have an associated Layout, which guides how to format the output. The Layout is responsible for formatting the log output in different layouts. User can control the output format by modifying the Log4J configuration file.

There are basically three types of Layout:

  1. HTMLLayout : It formats the output in the HTML table
  2. PatternLayout : It formats the output in the conversion pattern
  3. SimpleLayout : It formats the output in a simple manner, it prints the level then place a dash and then the user specified log message.

Configuring Log4J

For running application using Log4J you need to download

the latest version log4j jar file and then add this to the classpath.

There are two ways to configure the Log4J one is by using properties file and other by using xml file. Using xml for Log4J is quite popular and it is recommended also.

In the next section we will download Log4J libraries, install and then run a small program.

 

 

log4j.xml Example

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >

<log4j:configuration>

 <appender name="stdout" class="org.apache.log4j.ConsoleAppender">

   <layout class="org.apache.log4j.PatternLayout">

     <param name="ConversionPattern" value="%d{ABSOLUTE} 
      %5p %c{1}:%L - %m%n"/>

	</layout>

     </appender>

       <root>

	  <priority value="debug"></priority>

	  <appender-ref ref="stdout"/>

	</root>

</log4j:configuration>
 

Log4j looks for log4j.xml file first and then go for log4j.properties hence you must place both the files in your folder. We use log4j.xml since properties file does not provide some advanced configuration options such as Filter , some of ErrorHandlers, and few advanced Appenders .

log4j.properties

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{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=debug, stdout
 

 

Here is our SimpleLog class code:

SimpleLog.java   

 import  org.apache.log4j.*;
public class  SimpleLog  {
   static  Logger logger = Logger.getLogger ( "SimpleLog.class" ) ;
   public static  void  main ( String []  args ) {
     logger.debug ( "Welcome to Log4j" ) ;  
     }
} 
 

 

 

Layouts in Log4j

Users more often wish to customize their output according to their output format. Layout can be set by attaching it with the appender. The Layout is responsible for formatting the logging output.

There are following layout classes in Log4j:

  • PatternLayout
  • SimpleLayout
  • HTMLLayout
  • XMLLayout
  • TTCCLayout

Pattern Layout :

In our this section we are describing about most general layout PatternLayout . It is a flexible layout configurable with its pattern string. A conversion pattern consists of literal text and format control expressions. Here is the list of some of the conversion characters used for formatting:

   Character  Effect
c Used to output the category of logging event
C Used to output the fully qualified class name of the caller issuing the logging request
d Used to output date of the logging event
m Used to output the application supplied message associated with the logging event
n Outputs the platform dependent line separator character or characters

p

Used to output the priority of the logging event
r Used to output the number of milliseconds elapsed from the construction of the layout until the creation of the logging event
t Used to output name of thread of logging event
F Used to output the file name
  13:07:40,875 DEBUG class:5 - Welcome to Log4j

<!-- google_ad_section_start --> <!-- Top --> <!-- Left -->

A simple example of log4j for Servlet

his Example shows you how to create a log in a Servlet.

Description of the code:

Logger.getLogger(): Logger class is used for handling the majority of log operations and getLogger method is used for return a logger according to the value of the parameter. If the logger already exists, then the existing instance will be returned. If the logger is not already exist, then create a new instance.

log.info(): This method is used to check that the specified category is INFO enabled or not, if yes then it converts the massage passed as a string argument to a string by using appropriate object renderer of class ObjectRenderer.

 

LoggingServlet :

import  java.io.IOException;
import  java.io.PrintWriter;

import  javax.servlet.ServletException;
import  javax.servlet.http.HttpServlet;
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;

import  org.apache.log4j.Logger;

public class  LoggingServlet  extends  HttpServlet  {

     private static  Logger logger = Logger.getLogger ( LoggingServlet. class ) ;

     protected  void  processRequest ( HttpServletRequest request, 
                   HttpServletResponse response )

             throws  ServletException, IOException  {
         response.setContentType ( "text/html;charset=UTF-8" ) ;
         PrintWriter writer = response.getWriter () ;
         try  {
             logger.info ( "invoked the LoggingServlet..." ) ;
             writer.println ( "Check your web server  console..." ) ;
             writer.flush () ;
             writer.close () ;
         }  finally  {
             writer.close () ;
         }
     }

     protected  void  doGet ( HttpServletRequest request, 
    HttpServletResponse response )

             throws  ServletException, IOException  {
         processRequest ( request, response ) ;
     }

     protected  void  doPost ( HttpServletRequest request, 
    HttpServletResponse response )

             throws  ServletException, IOException  {
         processRequest ( request, response ) ;
     }
} 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值