【发布时间】:2023-03-12 15:30:01
【问题描述】:
在将项目从 log4j 迁移到 log4j2 时,我遇到了一种情况,即必须在运行时添加将事件记录到单独文件(我们称之为 uu.log)的记录器 - 所有其他记录器都在属性文件中配置。下面的代码几乎可以完成这项工作 - 即,uu.log 包含来自所有现有记录器的事件,而不仅仅是来自新记录器的事件。这是我到目前为止所尝试的:如何修复下面的代码以最简单的方式实现所需的状态?
public class MultipleLoggersExample {
public static void main(String[] args) throws InterruptedException {
// this logger is configured in properties file and is logging to own file
Logger aud = LogManager.getLogger("aud");
// class B is logging to separate file (logger also defined in properties)
B b = new B();
// below classes should log to common file NormalLog.log defined in properties
C c = new C();
D d = new D();
E e = new E();
addLoggerAtRuntime();
// this logger needs to log only its OWN messages to uu.log file
Logger runtimeLogger = LogManager.getLogger("my runtime logger");
int counter = 2;
while(true) {
if(counter % 2 == 0){
aud.info("message from \"aud\" logger no. "+ (counter-1));
} else{
b.logger.info("message from class B no. " + (counter-1));
}
c.logger.info("message from class C");
e.logger.info("message from class E");
if(counter % 4 == 0) {
runtimeLogger.info("message from logger added at runtime");
}
counter++;
Thread.sleep(5_000);
}
}
private static void addLoggerAtRuntime() {
final String fileName = "C:\\Users\\Damian\\Desktop\\uu.log";
LoggerContext lc = (LoggerContext) LogManager.getContext(false);
RollingFileAppender rfa = RollingFileAppender.newBuilder()
.withName("my runtime logger").withAppend(true)
.withFileName(fileName)
.withLayout(PatternLayout.newBuilder().withPattern("%-5p %d [%t] %C{2} - %m%n").build())
.withPolicy(TimeBasedTriggeringPolicy.newBuilder().withModulate(true).withInterval(2).build())
.withFilePattern(fileName + "." + "%d{yyyy-MM-dd-HH-mm}")
.setConfiguration(lc.getConfiguration()).build();
rfa.start();
lc.getConfiguration().addAppender(rfa);
lc.getRootLogger().addAppender(lc.getConfiguration().getAppender(rfa.getName()));
lc.updateLoggers();
}
}
【问题讨论】: