Java 如何使用log4j写入文本文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4474646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:53:49  来源:igfitidea点击:

how to write to a text file using to log4j?

javaloggingfilelog4j

提问by RanZilber

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");
    }
}

The properties file is :

属性文件是:

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

Thanks.

谢谢。

采纳答案by DwB

Change the ConsoleAppender to a FileAppender.

将 ConsoleAppender 更改为 FileAppender。

I find the org.apache.log4j.RollingFileAppenderto 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):

我觉得org.apache.log4j.RollingFileAppender很有用。如果使用它,则必须为 fileName 添加一个属性,并且可能还想设置 maxFileSize。这是一个示例(将它们放在 log4j.properties 文件中):

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

There are other appenders. DailyRollingFileAppenderrolls based on time. FileAppenderdoes 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.

还有其他附加程序。 DailyRollingFileAppender根据时间滚动。 FileAppender不滚动。如果您使用RollingFileAppender,则需要猜测 maxFileSize 的合适值,然后在未来某个日期解决导致问题的大小。

回答by AlexR

Shortly use FileAppender instead of ConsoleAppender.

很快使用 FileAppender 而不是 ConsoleAppender。

Here is a simple example of configuration. It additionally configures the layout. You can omit it for the first approach.

下面是一个简单的配置示例。它还配置了布局。对于第一种方法,您可以省略它。

log4j.appender.F=org.apache.log4j.FileAppender
log4j.appender.F.File=mylog.log
log4j.appender.F.layout=org.apache.log4j.PatternLayout
log4j.appender.F.layout.ConversionPattern=%d{MM-dd@HH:mm:ss} %-5p (%13F:%L) %3x - %m%n

回答by Muhammad Abid

following configuration should aslo work

以下配置应该也可以工作

direct log messages to stdout ###

将日志消息直接发送到标准输出 ###

log4j.appender.stdout=org.apache.log4j.FileAppender
log4j.appender.stdout.fileName=error.log
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.appender.stdout=org.apache.log4j.FileAppender
log4j.appender.stdout.fileName=error.log
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=% d{绝对} %5p %c{1}:%L - %m%n

回答by Thailand

in log4j.properties

在 log4j.properties 中

# Define the root logger with file appender
log4j.logger.App = DEBUG ,CA

#set file text
log4j.appender.CA = org.apache.log4j.RollingFileAppender
log4j.appender.CA.File = D:\database.log
log4j.appender.CA.maxFileSize = 20MB
log4j.appender.CA.MaxBackupIndex=10
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

回答by harshainfo

The following would be helpful:

以下内容会有所帮助:

Class containing main method

包含主要方法的类

    package abc;

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

    public class ClassOne {
        static Logger logger = Logger.getLogger(ClassOne.class);

        public static void main(String[] args) {
             PropertyConfigurator.configure("log4j.info"); //log4j.info file should be in the class path(same location as ClassOne.class)

             logger.info("Program started.... "); //Whenever you want to write something to the log text file use logger.info("Log Message")

        }
    }

log4j.info file

log4j.info 文件

   log4j.rootLogger=INFO, FILE

   # Define the file appender
   log4j.appender.FILE=org.apache.log4j.FileAppender // Replacing ConsoleAppender with FileAppender gives text file logging

   # Set the name of the file
   log4j.appender.FILE.File=src/abc/log.out //Here you can specify either absolute or relative path

   # Set the immediate flush to true (default)
   log4j.appender.FILE.ImmediateFlush=true

   # Set the threshold to debug mode
   log4j.appender.FILE.Threshold=debug

   # Set the append to false, overwrite
   log4j.appender.FILE.Append=false

   # Define the layout for file appender
   log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
   log4j.appender.FILE.layout.conversionPattern=%d %m%n