如何使用log4j写入文本文件? [英] how to write to a text file using to log4j?

查看:127
本文介绍了如何使用log4j写入文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何转换以下代码以将这些行输出到文本文件中,而不是标准输出:

I'm wondering how to convert the following code to output those lines into a text file, and not to standard output:

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

public class HelloWorld {

    static final Logger logger = Logger.getLogger(HelloWorld.class);

    public static void main(String[] args) {
        PropertyConfigurator.configure("log4j.properties");
        logger.debug("Sample debug message");
        logger.info("Sample info message");
        logger.warn("Sample warn message");
        logger.error("Sample error message");
        logger.fatal("Sample fatal message");
    }
}

属性文件是:

log4j.rootLogger=DEBUG, CA
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.FA.layout.ConversionPattern=%m%n

谢谢。

推荐答案

将ConsoleAppender更改为FileAppender。

Change the ConsoleAppender to a FileAppender.

我发现 org.apache.log4j.RollingFileAppender
很有用。
如果你使用这个,
你必须为fileName添加一个属性,
也可能想要设置maxFileSize。
这是一个例子(将它们放在log4j.properties文件中):

I find the org.apache.log4j.RollingFileAppender to be useful. If you use this, you must add a property for the fileName and may want to set the maxFileSize as well. Here is an example (put these in the log4j.properties file):

log4j.appender.NotConsole=org.apache.log4j.RollingFileAppender
log4j.appender.NotConsole.fileName=/some/path/to/a/fileName.log
log4j.appender.NotConsole.maxFileSize=20MB

还有其他appender。
DailyRollingFileAppender 根据时间滚动。
FileAppender 不会滚动。
如果您使用 RollingFileAppender
,您需要猜测maxFileSize和
的良好值,然后在未来日期,如果它导致问题。

There are other appenders. DailyRollingFileAppender rolls based on time. FileAppender does not roll. If you use the RollingFileAppender, you will need to guess as to a good value for maxFileSize and then address the size at a future date if it is causing issues.

这篇关于如何使用log4j写入文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆