Home > Java > javaTutorial > body text

Use Log4j to configure log output application details for projects and implementation analysis of sample demonstrations

高洛峰
Release: 2017-01-18 13:12:39
Original
1275 people have browsed it

Log4j component composition

Log4j is composed of three important components:

1. The priority of log information (Logger)

2. The output purpose of log information Appender

3. Output format (Layout) of log information.

Summary:

The priorities of log information from high to low are ERROR, WARN, INFO, and DEBUG, which are used to specify the importance of this log information respectively;

The output destination of the log information specifies whether the log will be printed to the console or a file;

and the output format controls the display content of the log information.

Introduction to Log4j

Log4j is an open source project of Apache. By using Log4j, we can control the destination of log information transmission to the console, files, GUI components, and even sockets. Server, NT event recorder, UNIX Syslog daemon, etc.; we can also control the output format of each log. By defining the level of each log information, we can control the log generation process in more detail. log4j-- log for java (java log) .

Log4j download address: http://logging.apache.org/log4j/2.x/download.html

Log4j configuration file The format

Log4j supports two configuration file formats:

1. XML format file

2. Properties format file

You can also use it completely Use configuration files instead to configure the Log4j environment in code. However, using configuration files will make your application more flexible.

Log4j definition configuration file

1. Configure the root Logger

The syntax is:

log4j.rootLogger = [ level ] , appenderName, appenderName, …
Copy after login

Parameter description:

level is the log The priority of the record is divided into OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or the level you define.

Off: The highest level, used to turn off all logging

Fatal: Indicates that each serious error event will cause the application to exit.

Error: Indicates that although an error event occurs, it still does not affect the continued operation of the system.

Warn: Indicates that potential error situations will occur

Info: Generally used at the coarse-grained level, emphasizing the entire running process of the application

Debug: Generally used at the coarse-grained level level, emphasizing the entire running process of the application.

All: The lowest level, used to turn on all logging.

Log4j recommends using only four levels. The priorities from high to low are ERROR, WARN, INFO, and DEBUG. Through the levels defined here, you can control the on and off of the corresponding level of log information in the application.

appenderName refers to where the log information is output, and multiple output destinations can be specified at the same time.

2. Configure the log information output destination Appender

The syntax is:

log4j.appender.appenderName = fully.qualified.name.of.appender.class  
log4j.appender.appenderName.option1 = value1  
...  
log4j.appender.appenderName.option = valueN
Copy after login

The appenders provided by Log4j are as follows:

 org.apache .log4j.ConsoleAppender (console)

org.apache.log4j.FileAppender (file)

org.apache.log4j.DailyRollingFileAppender (generates a log file every day)

org.apache.log4j.RollingFileAppender (Generate a new file when the file size reaches the specified size)

org.apache.log4j.WriterAppender (Send log information to any specified place in streaming format)

3. Configure the format of log information

The syntax is:

log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
log4j.appender.appenderName.layout.option1 = value1 …
log4j.appender.appenderName.layout.option = valueN
Copy after login

The layouts provided by Log4j are as follows:


org.apache.log4j.HTMLLayout (layout in HTML table format),

org.apache.log4j.PatternLayout (layout mode can be flexibly specified),

org. apache.log4j.SimpleLayout (contains the level and information string of the log information),

org.apache.log4j.TTCCLayout (contains the time, thread, category, etc. of the log generation)

Log4J uses a printing format similar to the printf function in C language to format log information. The printing parameters are as follows:

%m Output the message specified in the code

%p Output priority, that is, DEBUG, INFO, WARN, ERROR, FATAL

%r Output the number of milliseconds it took from the application startup to the output of the log information

%c The category to which the output belongs, usually the full name of the class

%t Output the name of the thread that generated the log event

%n Output a carriage return and line feed character, "rn" for Windows platform, "n" for Unix platform

% d Output the date or time of the log time point. The default format is ISO8601. You can also specify the format afterwards, such as: %d{yyy MMM dd HH:mm:ss,SSS}. The output is similar: October 18, 2002 22 :10:28,921  

%l Output the location where the log event occurred, including the category name, the thread where it occurred, and the number of lines in the code. Example: Testlog4.main(TestLog4.java:10)

%x: Outputs the NDC (nested diagnostic environment) associated with the current thread, especially for multi-client and multi-thread applications like java servlets middle.

%%: Output a "%" character %F: Output the file name where the log message is generated

%L: Output the line number in the code

%m : Output the message specified in the code, the specific log information generated

%n: Output a carriage return and line feed, the Windows platform is "\r\n", the Unix platform is "\n" and the output log information is line feed. You can add modifiers between % and the pattern character to control its minimum width, maximum width, and text alignment.

如:

1)%20c:指定输出category的名称,最小的宽度是20,如果category的名称小于20的话,默认的情况下右对齐。

2)%-20c:指定输出category的名称,最小的宽度是20,如果category的名称小于20的话,”-”号指定左对齐。

3)%.30c:指定输出category的名称,最大的宽度是30,如果category的名称大于30的话,就会将左边多出的字符截掉,但小于30的话也不会有空格。

4)%20.30c:如果category的名称小于20就补空格,并且右对齐,如果其名称长于30字符,就从左边交远销出的字符截掉。

log4j.xml的配置方式

View Code
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="appender1"
        class="org.apache.log4j.RollingFileAppender">
        <param name="File" value="logfile08.html" />
        <param name="MaxFileSize" value="1MB" />
        <param name="MaxBackupIndex" value="5" />
        <layout class="org.apache.log4j.HTMLLayout">
        </layout>
    </appender>
    <root>
        <level value="debug" />
        <appender-ref ref="appender1" />
    </root>
</log4j:configuration>
Copy after login

代码中使用Log4j


  在程序中使用 Log4j之前,首先要将commons-logging.jar和logging-log4j-1.2.9.jar导入到classpath中,并将 log4j.properties放于src根目录中。 在类中使用log4j,首先声明一个静态变量 Logger logger=Logger.getLog("classname").现在就可以使用了。

用法如下:logger.debug("debug message")或者logger.info("info message").

1.得到记录器

  使用Log4j,第一步就是获取日志记录器,这个记录器将负责控制日志信息。

其语法为:

  public static Logger getLogger( String name)

  通过指定的名字获得记录器,如果必要的话,则为这个名字创建一个新的记录器。Name一般取本类的名字,比如:

  static Logger logger = Logger.getLogger ( ServerWithLog4j.class.getName () )

2.读取配置文件

  当获得了日志记录器之后,第二步将配置Log4j环境,其语法为:

  BasicConfigurator.configure (): 自动快速地使用缺省Log4j环境。

  PropertyConfigurator.configure ( String configFilename) :读取使用Java的特性文件编写的配置文件。

  DOMConfigurator.configure ( String filename ) :读取XML形式的配置文件。

3.插入记录信息(格式化日志信息)

  当上两个必要步骤执行完毕,您就可以轻松地使用不同优先级别的日志记录语句插入到您想记录日志的任何地方,语法如下:

   Logger.debug ( Object message ) ;

   Logger.info ( Object message ) ;

   Logger.warn ( Object message ) ;

   Logger.error ( Object message ) ;

程序演示

1.使用程序进行日志信息输出

package org.demo.log4j.dennisit;

 import java.io.IOException;

 import org.apache.commons.logging.impl.Log4JLogger;
 import org.apache.log4j.BasicConfigurator;
 import org.apache.log4j.FileAppender;
 import org.apache.log4j.Layout;
 import org.apache.log4j.Level;
 import org.apache.log4j.Logger;
 import org.apache.log4j.SimpleLayout;

 /**
  *
  *  @version : 1.1
  *  
  *  @author  : 苏若年    <a href="mailto:DennisIT@163.com">发送邮件</a>
  *    
  *  @since      : 1.0        创建时间:    2013-1-1        下午03:19:42
  *     
  *  @function: 通过代码将日志输出
  *
  */

 public class Log4jPrintByCode {

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

     private Layout layout = new SimpleLayout();
     private FileAppender fileAppender;

 
     //使用构造依赖,创建对象时初始化
     public Log4jPrintByCode(Layout layout, Level level,String distDir){

         BasicConfigurator.configure();        //使用默认的配置信息,不需要写log4j.properties

         try {
             init(layout,level, distDir);
         } catch (Exception e) {
             e.printStackTrace();
         }

     }

     
     public void init(Layout layout, Level level,String distDir) throws Exception{

         logger.setLevel(level);                //设置日志输出级别
         fileAppender = new FileAppender(layout,distDir,false);
         logger.addAppender(fileAppender);    //添加输出端

     }

     
     public static void main(String[] args) {

         SimpleLayout layout = new SimpleLayout();
         String logDir = "log4jcode.Log";
         Log4jPrintByCode log4jCode = new Log4jPrintByCode(layout,Level.INFO,logDir);

         
         //下面信息将被输出
         log4jCode.logger.info("log info print by log4j");
         log4jCode.logger.warn("log warn print by log4j");
         log4jCode.logger.error("log error print by log4j");

     }

 
     public Layout getLayout() {
         return layout;
     }

     public void setLayout(Layout layout) {
         this.layout = layout;
     }

     public FileAppender getFileAppender() {
         return fileAppender;
     }

     public void setFileAppender(FileAppender fileAppender) {
         this.fileAppender = fileAppender;
     }

     

 }
Copy after login

为了提高效率,我们可以在写日志前增加判断:

// 记录debug级别的信息
if (logger.isDebugEnabled()) {
    logger.debug("This is debug message from Dao.");
}
// 记录info级别的信息
if (logger.isInfoEnabled()) {
    logger.info("This is info message from Dao.");
}
Copy after login

如果这个类作为基类,如J2EE中的BaseDao、BaseAction、BaseService等等,则我们可以将各层的日志信息分类输出到各个文件。

2.Log4J将同一个日志信息输出到多个目的地

/* 创建数据库 */ 
create database db_log4j;
/* 切换数据库 */
use  db_log4j;
/* 日志信息表 */
create table tb_log(
    logId int not null auto_increment comment &#39;流水号&#39; ,
    createDate varchar(45) default null comment &#39;日志生成时间&#39; ,
    thread varchar(45) default null comment &#39;当前线程&#39;,
    level varchar(45) default null comment &#39;当前日志级别&#39; ,
    class varchar(45) default null comment &#39;生成日志的类&#39;,
    message varchar(245) default null comment &#39;日志具体信息&#39;,
    primary key(logId)
);
Copy after login
Copy after login

应用实例将日志信息同时输出到控制台,文件和数据库中.

创建数据库与 表

/* 创建数据库 */ 
create database db_log4j;
/* 切换数据库 */
use  db_log4j;
/* 日志信息表 */
create table tb_log(
    logId int not null auto_increment comment &#39;流水号&#39; ,
    createDate varchar(45) default null comment &#39;日志生成时间&#39; ,
    thread varchar(45) default null comment &#39;当前线程&#39;,
    level varchar(45) default null comment &#39;当前日志级别&#39; ,
    class varchar(45) default null comment &#39;生成日志的类&#39;,
    message varchar(245) default null comment &#39;日志具体信息&#39;,
    primary key(logId)
);
Copy after login
Copy after login

配置文件log4j.properties

#定义3个输出端
log4j.rootCategory=INFO,A1,A2,A3
#定义A1输出到控制器
log4j.appender.A1=org.apache.log4j.ConsoleAppender
#定义A1的布局模式为PaternLayout
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
# 定义A1的输出格式
log4j.appender.A1.layout.ConversionPattern=%4p [%t] (%F:%L) - %m%n
#定义A2输出到文件
log4j.appender.A2=org.apache.log4j.RollingFileAppender
#定义A2输出到哪个文件
log4j.appender.A2.File=./log/sysLog.log
#定义A2输出文件的最大长度
log4j.appender.A2.MaxFileSize = 1KB
#定义A2的备份文件数
log4j.appender.A2.MaxBackupIndex = 3
#定义A2的布局模式为PatternLayout
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
#定义A2的输出模式
log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm:ss}:%p %t %c - %m%n
#定义A3输出到数据库
log4j.appender.A3=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.A3.URL=jdbc:mysql://localhost:3306/db_log4j
log4j.appender.A3.driver=com.mysql.jdbc.Driver
log4j.appender.A3.user=root
log4j.appender.A3.password=root
#定义A3的布局和执行的SQL语句
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.layout.ConversionPattern=INSERT INTO tb_log(createDate,thread,level,class,message) values(&#39;%d&#39;,&#39;%t&#39;,&#39;%-5p&#39;,&#39;%c&#39;,&#39;%m&#39;)
Copy after login

Java测试代码

package org.demo.log4j.dennisit;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
 *
 *  @version : 1.1
 *  
 *  @author  : 苏若年    <a href="mailto:DennisIT@163.com">发送邮件</a>
 *    
 *  @since      : 1.0        创建时间:    2013-1-1        下午04:13:59
 *     
 *  @function: 通过配置文件控制日志信息输出到多个目的端
 *
 */
public class Log4jPrintByConfigure {

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

    public static void main(String[] args) throws Exception {
        //加载log配置文件log4j.properties
        PropertyConfigurator.configure("configure/log4j.properties");//文件存放在src同目录的configure文件夹下

        //如果放在src下的话,参数应为"bin/log4j.properties"或者"src/log4j.properties", 建议以bin为准

        //以下信息将被打印输出
        logger.debug("logger print DEBUG messgae");
        logger.info("logger print INFO message");
        logger.warn("logger print WARN message");
        logger.error("logger print ERROR message");
        logger.fatal("Here is FATAL message");
    }
}
Copy after login

更多使用Log4j为项目配置日志输出应用详解以及示例演示的实现分析相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!