获取log4j2中的文件的文件名

时间:2018-11-08 14:57:56

标签: java logging log4j log4j2

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

library(dplyr)
library(zoo) # for the na.locf function
data %>% 
  group_by(ts_id) %>% # group by id
  mutate(value = na.locf(value,na.rm=F)) # na.locf fills with the last non-empty value

#head()
# # A tibble: 6 x 3
# # Groups:   ts_id [2]
# ts_id date       value
# <dbl> <date>     <dbl>
# 1     2 2014-10-01    18
# 2     2 2014-11-01    15
# 3     2 2014-12-01    15
# 4     2 2015-01-01    15
# 5     2 2015-02-01    15
# 6     3 2015-03-01    19

我编写了一个类... <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> ... ,该类扩展了CustomStrategy,然后覆盖了方法DefaultRolloverStrategy,如下所示:

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])吗?

1 个答案:

答案 0 :(得分:0)

已滚动的文件实际上位于代码中temp变量的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;
    }
}