Log4j2:动态创建多个日志的日志文件

spa*_*ion 5 java logging log4j log4j2

我目前正在创建一个可以拥有模块的系统(将它们视为插件),其中每个模块都可以拥有自己的专用日志.

我想使用log4j2项目进行日志记录,但我似乎对文件appender有些麻烦.

主项目(模块加载器和整个事物的"核心")应该有自己的日志文件,而模块应该有自己的(如mod_XXXXXXXX.log).

通过阅读有关appender的文档,我发现了这个FileAppender类,我打算使用它.直到我发现我不能简单地将appender添加到由创建的默认记录器LogManager.getLog().

LogManager返回的记录器是与Logger接口不同的记录器.

甚至搜索都没有给我任何近乎解决方案,我发现只是xml配置中的预定义文件日志 - 这不是我想要的.

谢谢你的阅读; 即使是最轻微的线索也欢迎:)

Rem*_*pma 9

if you really need to determine the log file dynamically, take a look at the Log4J2 RoutingAppender. A longer example is in the FAQ and these stackoverflow questions may be of interest: Wildcard pattern for RoutingAppender of Log4j2 and How to write different logs in different files with log4j2 (MDC in xml)?

Note that you need to set values in the ThreadContext map that the RoutingAppender uses to decide which appender to route the log event to. This means that you would need to put some value in the ThreadContext map every time your code enters a different plugin.

However, do you really need it to be this dynamic? If you know in advance what plugins you have, you can just declare a logger for each plugin (using the package name of the plugin is a common way to do this), and map each such logger to a separate appender.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
  <Appenders>
    <File name="MyFile" fileName="logs/app.log">
      <PatternLayout>
        <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
      </PatternLayout>
    </File>
    <File name="plugin1" fileName="logs/plugin1.log">
      <PatternLayout>
        <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
      </PatternLayout>
    </File>
    <File name="plugin2" fileName="logs/plugin2.log">
      <PatternLayout>
        <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
      </PatternLayout>
    </File>
  </Appenders>
  <Loggers>
    <Logger name="com.mycomp.project.plugin1" level="debug">
      <AppenderRef ref="plugin1" level="debug" />
    </Logger>
    <Logger name="com.mycomp.project.plugin2" level="debug">
      <AppenderRef ref="plugin2" level="debug" />
    </Logger>
    <Root level="trace">
      <AppenderRef ref="MyFile" level="trace" />
    </Root>
  </Loggers>
</Configuration>
Run Code Online (Sandbox Code Playgroud)