How to rotate a log4j log manually

2019-02-25 08:29发布

问题:

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 - and if so: How?

Solved like this:

void rolloverLogs() {
    for(final Enumeration<?> loggers = LogManager.getCurrentLoggers(); loggers.hasMoreElements(); )  {

        final Logger logger = (Logger) loggers.nextElement();

        for (final Enumeration<?> appenders = logger.getAllAppenders(); appenders.hasMoreElements(); )  {

            final Appender a = (Appender) appenders.nextElement();

            if(!RollingFileAppender.class.isInstance(a))
                continue;

            ((RollingFileAppender)a).rollOver();
        }
    }
}

回答1:

If you're keeping track of your appenders, you could call

https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/RollingFileAppender.html#rollOver()

That should do it. I guess it's also possible to iterate through all appenders you can find starting from root level - just make sure you keep track of which appenders you already rolled.



回答2:

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


回答3:

For log4j2, you can use following.

    org.apache.logging.log4j.Logger logManagerLogger = LogManager.getLogger();
    Map<String, org.apache.logging.log4j.core.Appender> appenders = ((org.apache.logging.log4j.core.Logger) logManagerLogger).getAppenders();
    appenders.forEach((appenderName, appender) -> {
        if (appender instanceof RollingFileAppender) {
            logger.info("Rolling over appender " + appenderName);
            ((RollingFileAppender) appender).getManager().rollover();
        }
    });