每次我运行我的程序时都会创建Log4j-File,但我只想让它在日志级别为Errror及以上时创建一个文件。[英] Log4j - File is created every time I run my program, but I only want it to create a file when the log level is Errror and up

本文是小编为大家收集整理的关于每次我运行我的程序时都会创建Log4j-File,但我只想让它在日志级别为Errror及以上时创建一个文件。的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

在尝试log4j时,我有两个我想用不同的事情.

我有一个应该记录错误级别并达到文件,而另一个应该将所有内容记录到控制台的情况下.

控制台Appender似乎可以工作,但是Applender每次启动程序时都会继续创建一个新文件,即使我没有记录任何错误.我已经尝试将阈值设置为错误appender中的错误,但是文件仍然创建了程序的每一个运行,只是其中一无所有.

我的问题:我希望Applender在记录错误之前不创建新文件.目前,即使没有记录错误消息,也正在创建一个新的错误文件.

我正在使用log4j版本1.2.17,如果有所不同.

这是我的代码.帮助您非常感谢!

java:

public final class Sandbox {

    private static final Logger logger = Logger.getLogger(Sandbox.class);
    private static Sandbox instance;

    public Sandbox() {
        Thread.setDefaultUncaughtExceptionHandler(new ErrorFileLogger());
        instance = this;
        System.setProperty("file.date.format", Util.getDate("yyyy-MM-dd_HH-mm-ss"));
        DOMConfigurator.configure("log4j.xml");
//      PropertyConfigurator.configure("log4j.properties");
        logger.info("Creating " + Info.NAME + " " + Info.VERSION + " by " + Info.AUTHOR);
    }
}

public class ErrorFileLogger implements Thread.UncaughtExceptionHandler {

    private static Logger logger;
    private static final String s = System.lineSeparator();

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        logError(this.getClass(), t, e);
    }

    /**
     * Should be called when an uncaught exception is thrown or a caught exception is thrown.
     * @param c: The class where the error is coming from.
     * @param t: The thread the error occurred on.
     * @param e: The throwable, or actual error itself.
     */
    public static void logError(Class<?> c, Thread t, Throwable e) {
        logger = Logger.getLogger(c);
        logger.error(s + "---------- Sandbox Error Report ----------" + s + s + Util.getDate("dd/MM/yyyy HH:mm:ss")
                + s + s +"Uh oh, I'm going down. Save your self!" + s + s
                + "Details about the crash is listed below" + s
                + "---------------------------------------" + s + s +
                t.getName(), e);
    }
}

XML:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <!-- Error -->
    <appender name="ErrorFile"
         class="org.apache.log4j.RollingFileAppender">
        <param name="Threshold" value="error"/>
        <param name="file" value="./logs/error_report_${file.date.format}.log" />
        <param name="Append" value="false" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{HH:mm:ss}] [%p] [%c{1}]: %m%n" />
        </layout>
        <filter class="org.apache.log4j.varia.LevelMatchFilter">
            <param name="LevelToMatch" value="error"/> 
            <param name="AcceptOnMatch" value="true"/> 
        </filter>     
        <filter class="org.apache.log4j.varia.DenyAllFilter"/> 
    </appender>

    <!-- Console -->
    <appender name="Console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%p] [%c{1}]: %m%n" />
        </layout>

    </appender>


    <root>
        <appender-ref ref="ErrorFile"/>
        <appender-ref ref="Console"/>
    </root>

    </log4j:configuration>

另外,如果有人可以解释根源是什么及其重要性,那将是很棒的!

非常感谢, Andy608

推荐答案

创建新错误日志文件是正常行为.您必须在日志配置中添加rollingpolicy.超过100MB).

请检查GitHub的示例config xml

本文地址:https://www.itbaoku.cn/post/1575160.html

问题描述

upon experimenting with Log4j, I have two Appenders that I want to do different things with.

I have one that is supposed to log ERROR Levels and up to a file and another that is supposed to log everything no matter the level to the console.

The console Appender seems to work, but the error Appender continues to create a new file every time I start my program even if I am not logging any errors. I have tried setting Threshold to ERROR in the error Appender, but the file is still created every run of the program just with nothing in it.

My problem: I would like the Error Appender to not create a new file until an error is logged. Right now, a new error file is being created even if no error messages has been logged.

I am using log4j version 1.2.17 if that makes a difference.

Here is my code. Help is much appreciated!

Java:

public final class Sandbox {

    private static final Logger logger = Logger.getLogger(Sandbox.class);
    private static Sandbox instance;

    public Sandbox() {
        Thread.setDefaultUncaughtExceptionHandler(new ErrorFileLogger());
        instance = this;
        System.setProperty("file.date.format", Util.getDate("yyyy-MM-dd_HH-mm-ss"));
        DOMConfigurator.configure("log4j.xml");
//      PropertyConfigurator.configure("log4j.properties");
        logger.info("Creating " + Info.NAME + " " + Info.VERSION + " by " + Info.AUTHOR);
    }
}

public class ErrorFileLogger implements Thread.UncaughtExceptionHandler {

    private static Logger logger;
    private static final String s = System.lineSeparator();

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        logError(this.getClass(), t, e);
    }

    /**
     * Should be called when an uncaught exception is thrown or a caught exception is thrown.
     * @param c: The class where the error is coming from.
     * @param t: The thread the error occurred on.
     * @param e: The throwable, or actual error itself.
     */
    public static void logError(Class<?> c, Thread t, Throwable e) {
        logger = Logger.getLogger(c);
        logger.error(s + "---------- Sandbox Error Report ----------" + s + s + Util.getDate("dd/MM/yyyy HH:mm:ss")
                + s + s +"Uh oh, I'm going down. Save your self!" + s + s
                + "Details about the crash is listed below" + s
                + "---------------------------------------" + s + s +
                t.getName(), e);
    }
}

xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <!-- Error -->
    <appender name="ErrorFile"
         class="org.apache.log4j.RollingFileAppender">
        <param name="Threshold" value="error"/>
        <param name="file" value="./logs/error_report_${file.date.format}.log" />
        <param name="Append" value="false" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{HH:mm:ss}] [%p] [%c{1}]: %m%n" />
        </layout>
        <filter class="org.apache.log4j.varia.LevelMatchFilter">
            <param name="LevelToMatch" value="error"/> 
            <param name="AcceptOnMatch" value="true"/> 
        </filter>     
        <filter class="org.apache.log4j.varia.DenyAllFilter"/> 
    </appender>

    <!-- Console -->
    <appender name="Console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%p] [%c{1}]: %m%n" />
        </layout>

    </appender>


    <root>
        <appender-ref ref="ErrorFile"/>
        <appender-ref ref="Console"/>
    </root>

    </log4j:configuration>

Also, if anyone could explain what the root is and its importance that would be great!

Thanks so much, Andy608

推荐答案

creating new error log file is a normal behavior.You have to add RollingPolicy into the log configuration.You can configure time frequency(create new log file for every hour) or log file size basis (create new one after exceeding 100MB).

Please check sample config xml from github