-2

I am using rolling file appender in log4j2 and using time based triggering policy. Here is how my configuration file looks like:

...
<RollingFile name="RollingFile" fileName="logs/temp.log" filePattern="logs/test1-%d{MM-dd-yy-HH-mm-ss-SSS}.log">

        <Policies>
            <TimeBasedTriggeringPolicy interval="2"></TimeBasedTriggeringPolicy>
        </Policies>
        <JsonLayout eventEol="true" compact="true"></JsonLayout>
        <CustomStrategy />
</RollingFile>
...

I wrote a class CustomStrategy that extends DefaultRolloverStrategy and then I overrode method rollover as follows:

@Override
public RolloverDescription rollover(final RollingFileManager manager) throws SecurityException {

        RolloverDescription temp = super.rollover(manager);

        //Read file that just got rolled over and do some stuff

        return temp;
    }

In this method I need the name of the file that just got rolled over, i.e. initially logs are written to temp.log which are then rolled over to test1-[some timestamp], to read it and perform certain operations. Can anyone suggest on how to obtain the filename(test1-[some timestamp])?

shiva
  • 2,535
  • 2
  • 18
  • 32

1 Answers1

0

The rolled file is actually in the AsyncAction of the temp variable in your code. You can get the data you need using some java reflection. If you are using log4j2.6 or above the temp.getAsynchronous() returns a list of CompositeActions which you need to iterate over to find the ZipCompressAction.

Action asyncAction = temp.getAsynchronous();
ZipCompressAction zipCompressAction = asyncAction instanceof GzCompressAction ? (ZipCompressAction) asyncAction : null; // Or GzCompressAction - depends on your configuration

Field destination;
File destinationFile = null;

if (zipCompressAction != null) {
    try {
        destination = zipCompressAction.getClass().getDeclaredField("destination");
        Object destinationObject = ReflectionUtil.getFieldValue(destination, gzCompressAction);
        destinationFile = destinationObject instanceof File ? (File) destinationObject : null;
    } catch (Exception e) {
        destinationFile = null;
    }
}
Gal S
  • 980
  • 6
  • 17
  • I created my own custom strategy by copying the code from `DefaultRolloverStrategy` and stored the required filename in a `public static` variable. – shiva Nov 15 '18 at 05:50
  • @shiva I am not sure that copy the code and using static variable is the best solution as static [variables are against the OOP principles](https://stackoverflow.com/questions/7026507/why-are-static-variables-considered-evil). However, reflection also has its pitfalls... – Gal S Nov 15 '18 at 11:25