我正在开发一个可以生成不同日期时间的日志的程序。这是通过记录从实现TimestampMessage的自定义类创建的消息来实现的。
我尝试使用以下log4j2配置将这些日志输出到各自对应的文件中:
<Appenders>
<RollingFile name="Logs" filePattern="${log-path}/logs-%d{yyyy-MM-dd}">
<PatternLayout pattern="%d{dd MMM yyyy HH:mm:ss} %m%n" />
<Policies>
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
</Appenders>我本以为它会输出所有不同日期的日志文件,每个日期都有相应的日志,但我只得到了一个:格式化为当前日期。
但是,日志文件中包含的日志消息具有预期的日期,例如:
09 Mar 2007 10:23:11 BLABLA
30 Aug 2008 02:56:29 BLABLA
03 Dec 2009 10:20:34 BLABLA
10 Apr 2010 22:47:46 BLABLA
10 Apr 2010 22:59:31 BLABLA
13 Aug 2015 12:36:26 BLABLA在这里,我希望获得以下文件:
/log-path/logs-2007-03-09
/log-path/logs-2008-08-30
/log-path/logs-2009-12-03
/log-path/logs-2010-03-10
/log-path/logs-2015-08-13我认为这里最大的问题是RollingFile的filePattern使用当前日期,而我希望它使用日志消息日期,就像PatterLayout一样。
当然可以通过自定义附加器来解决我的问题,但在这里对我来说这听起来不是一个正确的解决方案,所以我想知道,有没有一种方法可以让RollingFile使用日志消息的日期而不是当前日期?
发布于 2021-06-22 03:34:25
最后,我找不到任何干净的方法来做到这一点,但是如果你遇到这个问题,有一个技巧可以做到:创建一个自定义的触发策略,它总是返回true,并将PatternProcessor的当前时间文件设置为事件的时间。
下面是一个例子:
@Plugin(name = "UnorderedLogTriggeringPolicy", category= Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE)
public class UnorderedLogTriggeringPolicy extends AbstractTriggeringPolicy {
RollingFileManager manager;
@Override
public boolean isTriggeringEvent(LogEvent logEvent) {
if (manager != null) {
// HACK: Set the time of the log File pattern processor using the time of the log event being processed
manager.getPatternProcessor().setCurrentFileTime(logEvent.getTimeMillis());
}
return true;
}
@Override
public void initialize(RollingFileManager manager) {
this.manager = manager;
manager.getPatternProcessor().setTimeBased(true);
}
@PluginFactory
public static UnorderedLogTriggeringPolicy createPolicy() {
return new UnorderedLogTriggeringPolicy();
}
}然后,您可以通过以下方式将其添加到log4j2.xml配置中:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO" shutdownHook="disable" packages="PACKAGE_CONTAINING_TRIGGERING_POLICY">
<Properties>
<Property name="log-path">/tmp/outdatedLogs</Property>
</Properties>
<Appenders>
<RollingFile name="OutdatedLogger" filePattern="${log-path}/%d{yyyy-MM-dd-HH}.logs">
<Policies>
<OutdatedLogEventTriggeringPolicy />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="INFO" additivity="false">
<AppenderRef ref="OutdatedLogger" level="INFO" />
</Root>
</Loggers>
</Configuration>再说一次,这可能不是这个问题的最干净的解决方案,但这已经足够了。希望这能对你有所帮助。
https://stackoverflow.com/questions/68039781
复制相似问题