Java:如何使用记录器将多个类记录到同一文件中?

时间:2018-12-03 09:21:29

标签: java log4j

我有一个主要的班级,说A类:

public class A {
    someMethod(){
        log.debug("inside some method in class A");
    }
}

然后是B类,其中:

public class B {
    someOtherMethod(){
        log.debug("inside some other method in class B");
    }
}

现在如何在此处使用记录器,即从这两个类登录并登录到公共日志文件? 属性文件的配置应该是什么?

1 个答案:

答案 0 :(得分:0)

如果您使用的是log4j,则可以向资源中添加一个config.properties文件:

# Root logger option
log4j.rootLogger=INFO, file, stdout

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
# this is the ouput file path and name
log4j.appender.file.File=filename.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Direct log messages to stdout
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{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

然后您可以像这样使用

import org.apache.log4j.Logger;

public class A {
    Logger log= Logger.getLogger(A.class);
    someMethod(){
       log.debug("inside some method in class A");
    }

public class B {
    Logger log= Logger.getLogger(B.class);
    someOtherMethod(){
        log.debug("inside some other method in class B");
    }
}