我正在将应用程序从 log4j
迁移到 log4j2
。请在下面找到从应用程序当前线程获取输入(例如模式为 mode1
)并将其附加到日志文件名(例如 log_mode1.log
)并创建附加程序并更新日志文件。
类别:
public class MultiFileAppender extends AppenderSkeleton {
...
@Override
protected void append(LoggingEvent event) {
...
}
@Override
public void close() {
}
@Override
public boolean requiresLayout() {
...
}
}
log4j.xml 中的附加程序内容:
<appender name="TEST_MULTIFILE" class="com.test.it.logging.MultiFileAppender">
<param name="File" value="${LOGS}/test/test_%id%.log"/>
<param name="Append" value="true"/>
<param name="MaxFileSize" value="500KB"/>
<param name="MaxBackupIndex" value="5"/>
<param name="Encoding" value="UTF-8"/>
</appender>
如何在java中获取这些参数并像log4j2中的上述配置一样创建多文件附加程序?请帮忙。谢谢。
最佳答案
假设以下场景:
一个类会被多次实例化,每个实例都有不同的 id。各个 id 的日志记录应该转到它自己的文件中。每个 id 一个文件。编写代码时 id 的值是未知的(当然是在本例中编写 Main
类时)。
public class Test implements Runnable {
private static final Logger LOG = LogManager.getLogger();
private final String id;
public Test(String id) {
this.id = id;
}
@Override
public void run() {
ThreadContext.put("id", id); //org.apache.logging.log4j.ThreadContext
while (true) {
try { Thread.sleep(10000); } catch (InterruptedException e) { break; }
LOG.info("{}: I have been sleeping for 10 seconds", id);
}
}
}
<小时/>
public class Main {
private static final Logger LOG = LogManager.getLogger();
public static void main(String[] args) {
LOG.info("Starting thread 1");
Thread t1 = new Thread(new Test("mode1"));
t1.start();
LOG.info("Starting thread 2");
Thread t2 = new Thread(new Test("mode2"));
t2.start();
LOG.info("Starting thread 3");
Thread t3 = new Thread(new Test("mode3"));
t3.start();
}
}
<小时/>
以下是log4j2的配置。
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<Appenders>
<Routing name="Routing">
<Routes pattern="$${ctx:id}">
<!-- If a special id should be treated differently
<Route key="mymode">
...
</Route> -->
<!-- Threads that don't have the id value set -->
<Route key="$${ctx:id}">
<File name="File"
fileName="normal.log">
<PatternLayout pattern="%d{HH:mm:ss} [%p] %c %msg%n" />
</File>
</Route>
<!-- Threads with the id value set, and is not one of the special ones above -->
<Route>
<File name="File-${ctx:id}"
fileName="id-${ctx:id}.log">
<PatternLayout pattern="%d{HH:mm:ss} [%p] %c %msg%n" />
</File>
</Route>
</Routes>
</Routing>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Routing" />
</Root>
</Loggers>
</Configuration>
<小时/>
这个想法取自 log4j2 FAQ 。另请参阅Lookups .
<小时/>如果您仍然需要让自定义附加程序与 log4j2 一起使用,也许 this question with answer为您提供了有关如何继续操作的一些很好的提示。
关于java - 如何在log4j2中实现多文件追加器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32949416/