Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4j2: how-to force rolling file appender to roll over?

To my best knowledge, RollingFileAppender in log4j2 will not roll over at the specified time (let's say - at the end of an hour), but at the first log event that arrives after the time threshold has been exceeded.

Is there a way to trigger an event, that on one hand will cause the file to roll over, and on another - will not append to the log (or will append something trivial, like an empty string)?

like image 551
Dan M Avatar asked Apr 09 '14 22:04

Dan M


3 Answers

No there isn't any (built-in) way to do this. There are no background threads monitoring rollover time.

You could create a log4j2 plugin that implements org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy (See the built-in TimeBasedTriggeringPolicy and SizeBasedTriggeringPolicy classes for sample code.)

If you configure your custom triggering policy, log4j2 will check for every log event whether it should trigger a rollover (so take care when implementing the isTriggeringEvent method to avoid impacting performance). Note that for your custom plugin to be picked up, you need to specify the package of your class in the packages attribute of the Configuration element of your log4j2.xml file.

Finally, if this works well for you and you think your solution may be useful to others too, consider contributing your custom triggering policy back to the log4j2 code base.

like image 183
Remko Popma Avatar answered Nov 27 '22 17:11

Remko Popma


Following Remko's idea, I wrote the following code, and it's working.

package com.stony;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.rolling.*;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;

@Plugin(name = "ForceTriggerPolicy", category = "Core")
public class ForceTriggerPolicy implements TriggeringPolicy {
private static boolean isRolling;

@Override
public void initialize(RollingFileManager arg0) {
    setRolling(false);
}

@Override
public boolean isTriggeringEvent(LogEvent arg0) {
    return isRolling();
}

public static boolean isRolling() {
    return isRolling;
}

public static void setRolling(boolean _isRolling) {
    isRolling = _isRolling;
}

@PluginFactory
public static ForceTriggerPolicy createPolicy(){
    return new ForceTriggerPolicy();
}

}
like image 25
Stony Avatar answered Nov 27 '22 18:11

Stony


If you have access to the Object RollingFileAppender you could do something like:

rollingFileAppender.getManager().rollover();

Here you can see the manager class:

https://github.com/apache/logging-log4j2/blob/d368e294d631e79119caa985656d0ec571bd24f5/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/RollingFileManager.java

like image 22
LightDragooon Avatar answered Nov 27 '22 16:11

LightDragooon