How to rotate a log4j log manually

前端 未结 3 1832
忘了有多久
忘了有多久 2021-01-20 15:04

I have log4j configured to rotate the log every day.

In special situations I would like to trigger an additional log rotation manually.

Is this possible - an

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-20 15:39

    The technique shown by Lahiru will only locate Appenders configured for a specific Logger which is based on the class the code resides in. The exact Appender(s) located may may vary if the configuration changes.

    If you know the Appender name the best way to do this is:

    org.apache.logging.log4j.core.LoggerContext context = LogManager.getContext(false);
    Appender appender = context.getConfiguration().getAppender(appenderName);
    if (appender instanceof RollingFileAppender) {
        ((RollingFileAppender) appender).getManager().rollover();
    }
    

    If you want to roll over all RollingFileAppenders you could do:

    org.apache.logging.log4j.core.LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
    for (Appender appender : context.getConfiguration().getAppenders().values()) {
        if (appender instanceof RollingFileAppender) {
            ((RollingFileAppender) appender).getManager().rollover();
        }
    }
    

提交回复
热议问题