【问题标题】:Get filename for rolled over file in log4j2获取 log4j2 中翻转文件的文件名
【发布时间】:2019-04-12 02:45:32
【问题描述】:

我在 log4j2 中使用滚动文件附加程序并使用基于时间的触发策略。这是我的配置文件的样子:

...
<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>
...

我编写了一个扩展DefaultRolloverStrategy 的类CustomStrategy,然后我覆盖了方法rollover,如下所示:

@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;
    }

在这种方法中,我需要刚刚翻转的文件的名称,即最初将日志写入temp.log,然后将其翻转到test1-[some timestamp],以读取它并执行某些操作。谁能建议如何获取文件名(test1-[some timestamp])?

【问题讨论】:

    标签: java logging log4j log4j2


    【解决方案1】:

    滚动文件实际上是在代码中临时变量的 AsyncAction 中。 您可以使用一些 java 反射来获取所需的数据。 如果您使用的是 log4j2.6 或更高版本,则 temp.getAsynchronous() 会返回一个 CompositeActions 列表,您需要对其进行迭代以找到 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;
        }
    }
    

    【讨论】:

    • 我通过从DefaultRolloverStrategy 复制代码创建了自己的自定义策略,并将所需的文件名存储在public static 变量中。
    • @shiva 我不确定复制代码并使用静态变量是静态variables are against the OOP principles 的最佳解决方案。然而,反射也有它的陷阱......
    猜你喜欢
    • 2014-11-06
    • 1970-01-01
    • 2018-07-26
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 2018-01-10
    相关资源
    最近更新 更多