【Log4j二】Log4j属性文件配置详解

如下是一个log4j.properties的配置

log4j.rootCategory=INFO, stdout , R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n

log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=/home/tom/logs/logs.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n

log4j.logger.com.tom=INFO, tom
log4j.appender.tom=org.apache.log4j.DailyRollingFileAppender
log4j.appender.tom.File=/home/tom/logs/tom.log
log4j.appender.tom.layout=org.apache.log4j.PatternLayout
log4j.appender.tom.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n


log4j.logger.pck=INFO, pck
log4j.appender.pck=org.apache.log4j.DailyRollingFileAppender
log4j.appender.pck.File=/home/tom/logs/pck.log
log4j.appender.pck.layout=org.apache.log4j.PatternLayout
log4j.appender.pck.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n

在这个配置文件中定义了三个logger,分别是root,com.tom以及pck,日志文件分别打印到logs.log,tom.log以及pck.log。

定义如下三个测试类

package com.tom.log4j;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;

public class Log4jTest {

    @org.junit.Test
    public void test1() {
        Log log = LogFactory.getLog("tom");
        log.info("Hello,test1");//输出到logs.log
    }

    @org.junit.Test
    public void test2() {
        Logger logger = Logger.getLogger(Log4jTest.class);
        logger.info("Hello, test2");//输出到logs.log以及tom.log
    }

    @org.junit.Test
    public void test3() {
        Logger logger = Logger.getLogger("pck"); //输出到logs.log以及pck.log
        logger.info("Hello, test3");
    }
}

 

test1结果分析

  • root logger会对所有的日志起作用,所以它会打印到root logger对应的日志文件logs.log
  • 因为配置中没有配置日志名称为tom的logger,因此,只有root logger会记录这个日志
  • 需要注意的是,如下定义的日志名称不是tom而是com.tom,因此通过getLogger("tom"),这个日志不会选中,也就不会打印到tom.log
log4j.logger.com.tom=INFO, tom
 

test2结果分析

  • root logger会对所有的日志起作用,所以它会打印到root logger对应的日志文件logs.log
  • Logger.getLogger(Log4jTest.class)会通过Log4jTest类文件的全限定名称(com.tom.log4j.Log4jTest)去查找日志。因为日志配置文件没有定义名称为com.tom.log4j.Log4jTest的logger,那它怎么写到tom.log文件中的呢?这就是Log4j的logger的继承关系,例如Logger.getLogger("X.Y.Z"),那么可以起作用的logger包括X.Y.Z,X.Y,X以及root。它不是从下向上找到就停止的方式,而是从它自身到root之间所有的logger找出来,然后根据每个logger的配置,进行日志打印。
  • 在test2中Logger.getLogger("com.tom.log4j.Log4jTest")会找到com.tom和root两个logger,因此分别打印到tom.log和logs.log

test3结果分析

  • root logger会对所有的日志起作用,所以它会打印到root logger对应的日志文件logs.log
  • 因为配置中有一个名称为pck的logger,因此这个logger也被选中,所以会打印到pck.log中

总结

     test2展现的logger的继承特性是非常有用,当在项目中使用了第三方的框架,例如Spring,Struts等,为了记录Spring,Struts的日志,可以在log4j.propeties添加两行

org.apache.struts=ERROR
org.springframework=WARN

 

也可以把它们记录到不同的文件中,例如:

log4j.logger.org.apache.struts=INFO, struts
log4j.appender.struts=org.apache.log4j.DailyRollingFileAppender
log4j.appender.struts.File=/home/tom/logs/struts.log
log4j.appender.struts.layout=org.apache.log4j.PatternLayout
log4j.appender.struts.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n

 


 layout格式

Conversion Character Effect
c Used to output the category of the logging event. The category conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.

If a precision specifier is given, then only the corresponding number of right most components of the category name will be printed. By default the category name is printed in full.

For example, for the category name "a.b.c" the pattern %c{2} will output "b.c".

C Used to output the fully qualified class name of the caller issuing the logging request. This conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.

If a precision specifier is given, then only the corresponding number of right most components of the class name will be printed. By default the class name is output in fully qualified form.

For example, for the class name "org.apache.xyz.SomeClass", the pattern %C{1} will output "SomeClass".

WARNING Generating the caller class information is slow. Thus, use should be avoided unless execution speed is not an issue.

d Used to output the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example, %d{HH:mm:ss,SSS} or %d{dd MMM yyyy HH:mm:ss,SSS}. If no date format specifier is given then ISO8601 format is assumed.

The date format specifier admits the same syntax as the time pattern string of the SimpleDateFormat. Although part of the standard JDK, the performance of SimpleDateFormat is quite poor.

For better results it is recommended to use the log4j date formatters. These can be specified using one of the strings "ABSOLUTE", "DATE" and "ISO8601" for specifying AbsoluteTimeDateFormat, DateTimeDateFormat and respectively ISO8601DateFormat. For example, %d{ISO8601} or %d{ABSOLUTE}.

These dedicated date formatters perform significantly better than SimpleDateFormat.

F Used to output the file name where the logging request was issued.

WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.

l Used to output location information of the caller which generated the logging event.

The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses.

The location information can be very useful. However, its generation is extremely slow and should be avoided unless execution speed is not an issue.

L Used to output the line number from where the logging request was issued.

WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.

m Used to output the application supplied message associated with the logging event.
M Used to output the method name where the logging request was issued.

WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.

n Outputs the platform dependent line separator character or characters.

This conversion character offers practically the same performance as using non-portable line separator strings such as "\n", or "\r\n". Thus, it is the preferred way of specifying a line separator.

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 the name of the thread that generated the logging event.
x Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event.
X

Used to output the MDC (mapped diagnostic context) associated with the thread that generated the logging event. The X conversion character must be followed by the key for the map placed between braces, as in %X{clientNumber} where clientNumber is the key. The value in the MDC corresponding to the key will be output.

See MDC class for more details.

% The sequence %% outputs a single percent sign.

log4j的maven依赖

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.2</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

使用slf4j的代码:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private final Logger LOG = LoggerFactory.getLogger("mylogger");

 第一行的第一个hc4是logger的名字,第二个hc4是logger的配置别名,这样,appender.hc4都是指代的第二个hc4.。

这种写法有个好处,就是

log4j.logger.org.apache.http=INFO,http,可以用http指代org.apache.http这个logger进行后面的配置

log4j.logger.hc4=INFO,hc4
log4j.appender.hc4=org.apache.log4j.DailyRollingFileAppender
log4j.appender.hc4.Threshold=DEBUG
log4j.appender.hc4.file=C:/http.client.logs/hc4.log
log4j.appender.hc4.DatePattern='.'yyyy-MM-dd
log4j.appender.hc4.layout=org.apache.log4j.PatternLayout
log4j.appender.hc4.layout.ConversionPattern=[%-5p] [%d{yyyy-MM-dd HH:mm:ss}] [%C{1}:%M:%L] %m%n
log4j.additivity.hc4=false

猜你喜欢

转载自bit1129.iteye.com/blog/2117180