如何为应用程序配置两个log4j

时间:2012-12-18 07:28:05

标签: java log4j

我需要为不同布局中的所有方法和类生成两个日志文件。有可能吗?

1 个答案:

答案 0 :(得分:0)

log4j.properties

log4j.rootLogger=error, file1, file2, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.file1=org.apache.log4j.RollingFileAppender 
log4j.appender.file1.File= file1.log
log4j.appender.file1.layout=org.apache.log4j.PatternLayout
log4j.appender.file1.layout.ConversionPattern=%p %t %c - %m%n <--- Different pattern 

log4j.appender.file2=org.apache.log4j.RollingFileAppender 
log4j.appender.file2.File= file2.log
log4j.appender.file2.layout=org.apache.log4j.PatternLayout
log4j.appender.file2.layout.ConversionPattern=%p (%F:%L) - %m%n <--- Different pattern 

SimplestCode.java

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class SimplestCode {

    static final Logger logger = Logger
            .getLogger(in.mdtareque.log4j.test.SimplestCode.class);

    public static void main(String[] args) {
        PropertyConfigurator.configure("resources/log4j.properties");

        logger.warn("WARN");
        logger.error("ERROR");
        logger.fatal("FATAL");

    }
}

日志文件在项目主目录中为上述配置创建。

file1.log

ERROR main in.mdtareque.log4j.test.SimplestCode - ERROR
FATAL main in.mdtareque.log4j.test.SimplestCode - FATAL

file2.log

ERROR (SimplestCode.java:18) - ERROR
FATAL (SimplestCode.java:19) - FATAL

Check more documentation here