How do I make log4j create log files on demand only?

前端 未结 4 1423
天命终不由人
天命终不由人 2020-12-16 02:12

We have a modular application where modules have their own log4j logs (i.e. communication log and error log). The appenders and categories for these are all configured in th

4条回答
  •  -上瘾入骨i
    2020-12-16 02:46

    Extend the standard FileAppender class was unsuccessful for me. So I have found an other solution using appenders programmatically to create log files on demand only (and with timestamp in the name file). I have written these two methods :

    public void startLog() {
        SimpleDateFormat sdf_long = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        FileAppender fa = new FileAppender();
        fa.setName("foo");
        fa.setFile(sdf_long.format(new Date()) + ".log");
        fa.setLayout(new PatternLayout("%d{HH:mm:ss.SSS} %m%n"));
        fa.setThreshold(Level.DEBUG);
        fa.setAppend(true);
        fa.activateOptions();
        Logger.getRootLogger().addAppender(fa);
    }
    
    public void stopLog() {
        Logger.getRootLogger().getAppender("foo").close();
        Logger.getRootLogger().removeAppender("foo");
    }
    

    My log4j.properties file only configures the console appender. When I want to start logging I call the startLog() method. When I want to log in an other file I call stopLog() first and then startLog() method.

提交回复
热议问题