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

只谈情不闲聊 提交于 2019-12-13 05:23:54

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/33886596/log4j-file-is-created-every-time-i-run-my-program-but-i-only-want-it-to-creat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!