简体   繁体   English

如何为所有类配置log4j fileappender?

[英]How to configure log4j fileappender for all classes?

In my application I read in an inputfile (eg myFile1.txt) and create an outputfile with the same name (eg myFile2log). 在我的应用程序中,我读入了一个输入文件(例如myFile1.txt)并创建了一个具有相同名称的输出文件(例如myFile2log)。 Point is that the inputfile will be read within the java application and not given as command line parameter. 要点是输入文件将在java应用程序中读取,而不是作为命令行参数给出。 Therefore it is required to set an appender in the application, eg 因此,需要在应用程序中设置一个appender,例如

public class Example {
private static final Logger LOG = Logger.getLogger(Example.class);

public Example() throws IOException {
    FileAppender appender = new DailyRollingFileAppender(new PatternLayout(
            PatternLayout.DEFAULT_CONVERSION_PATTERN), "yourfilename.log",
            "'.'yyyy-MM-dd");
    LOG.addAppender(appender);
    LOG.setLevel((Level) Level.DEBUG);
    LOG.debug("blabla");

    new RandomClass();
}

public static void main(String[] args) throws IOException {
    new Example();
}
}

public class RandomClass {
private static final Logger LOG = Logger.getLogger(RandomClass.class);

public RandomClass() {
    LOG.debug("hello Randomclass");
}
}

And here is the problem: if I do the above the custom file appender only works for the specific class where the fileappender was defined, but not on any other class. 这就是问题所在:如果我执行上述操作,则自定义文件appender仅适用于定义fileappender的特定类,但不适用于任何其他类。 Therefore the output of the "RandomClass" will not be written into this logfile, but which is what is required. 因此,“RandomClass”的输出不会写入此日志文件,但这是必需的。 How can I achieve that? 我怎样才能做到这一点?

You can use log4j.properties file in your class path then simply you can initilize logger in all the classes. 您可以在类路径中使用log4j.properties文件,然后只需在所有类中初始化logger。

private static final Logger LOG = Logger.getLogger(Example.class);

and Appender all not required in constructor. 并且构造函数中不需要Appender。 your property file should contain 您的属性文件应包含

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=yourfilename.log
log4j.appender.R.MaxFileSize=2048KB

If you would like to set the appender dynamically you should try setting the new appender to the root logger: 如果您想动态设置appender,您应该尝试将新的appender设置为根记录器:

Logger logger = Logger.getRootLogger();
FileAppender appender = new DailyRollingFileAppender(new PatternLayout(
   PatternLayout.DEFAULT_CONVERSION_PATTERN), "yourfilename.log", "'.'yyyy-MM-dd");
logger.addAppender(appender)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM