我想在我的程序中使用不同的记录器。每个记录器写入不同的文件。文件名是预定义的,不是动态的。例如,登录包将使用写入 login.log 文件的记录器。除文件名外,所有附加程序都相同。下面是一个程序的示例配置文件,该程序具有两个包“logging”和“test”:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
<Properties>
<Property name="log-location"> /home/roya/workspace/LogPractice/log</Property>
</Properties>
<Appenders>
<RollingFile name="logging" fileName="${log-location}/logging.log"
filePattern="${log-location}/$${date:yyyy-MM}/logging-%d{yyyy-MM-dd-HH}-%i.log.gz">
<PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="1 KB"/>
</Policies>
<DefaultRolloverStrategy max="5">
<!--
Nested conditions: the inner condition is only evaluated on files
for which the outer conditions are true.
-->
<Delete basePath="${log-location}" maxDepth="2">
<IfFileName glob="*/app-*.log.gz">
<IfLastModified age="30d">
<IfAny>
<IfAccumulatedFileSize exceeds="100 GB" />
<IfAccumulatedFileCount exceeds="10" />
</IfAny>
</IfLastModified>
</IfFileName>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
<RollingFile name="test" fileName="${log-location}/test.log"
filePattern="${log-location}/$${date:yyyy-MM}/test-%d{yyyy-MM-dd-HH}-%i.log.gz">
<PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="1 KB"/>
</Policies>
<DefaultRolloverStrategy max="5">
<!--
Nested conditions: the inner condition is only evaluated on files
for which the outer conditions are true.
-->
<Delete basePath="${log-location}" maxDepth="2">
<IfFileName glob="*/app-*.log.gz">
<IfLastModified age="30d">
<IfAny>
<IfAccumulatedFileSize exceeds="100 GB" />
<IfAccumulatedFileCount exceeds="10" />
</IfAny>
</IfLastModified>
</IfFileName>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="logging">
<AppenderRef ref="logging" level="ALL" />
</Logger>
<Logger name="test">
<AppenderRef ref="test" level="ALL" />
</Logger>
<Root level="ALL">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
如您所见,除了文件名之外,附加程序是相同的。有没有一种方法可以让我只定义一个附加程序并将文件名传递给记录器?
最佳答案
不,它们是不同的 Appender 实例,尽管它们的配置非常相似。 Log4j 2 不提供共享 Appender 配置部分的机制。
为了减少重复,您可以做的一件事是仅声明一次删除操作(在其中一个附加程序上,并使其匹配多个文件,以便覆盖所有附加程序。
您还可以在 log4j2 问题跟踪器或邮件列表上提出功能请求。
关于java - Log4j2 多个记录器具有相同的附加程序但文件名不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39598192/