Log4j2 - 查找插件 (StrLookup) 解析 ThreadName 以通过 Thread 路由 RollingLogFile

Log4j2 - Lookup Plugin (StrLookup) to resolve ThreadName for routing RollingLogFile via Thread

我正在尝试配置 log4j2 配置以通过线程名称将消息路由到多线程程序的不同日志文件。

到目前为止,这是我所拥有的(与 log4j2 配置相关):

|-/src/main/java/log4j2/plugins
|-- ThreadLookup.java
|-/src/main/resources
|-- log4j2.xml

ThreadLookup.java:

package log4j2.plugins;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.StrLookup;

@Plugin(name="threadLookup", category=StrLookup.CATEGORY)
public class ThreadLookup implements StrLookup {

    @Override
    public String lookup(String key) {
        return Thread.currentThread().getName();
    }

    @Override
    public  String lookup(LogEvent event, String key) {
        // Check event first:
        if (event.getThreadName() != null) {
            return event.getThreadName();
        }
        // Fallback to key if event doesn't define a threadName:
        return this.lookup(key);
    }

}

Log4j2.xml我的理解是Configurationpackages属性应该读入ThreadLookup.java 并根据注释创建一个新的 threadLookup 前缀,让我可以用我想要的任何值调用 lookup(String key)——在这种情况下,我没有使用特定值,因为这个 class只会进行线程名称查找):

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="error" strict="true" schema="Log4J-V2.0.xsd"
               packages="log4j2.plugins">
    <Properties>
        <Property name="logMsgPattern">%date{yyyy/MM/dd HH:mm:ss.SSS} %-5level ${sys:pid}[%thread] %class %method:%line - %message%n</Property>
    </Properties>

    <Appenders>

        <Console name="console" target="SYSTEM_OUT" >
            <PatternLayout pattern="${logMsgPattern}" />
        </Console>

        <Routing name="routing">
            <Routes pattern="$${threadLookup:threadName}">
                <Route>
                    <RollingFile name="RollingFile-${threadLookup:threadName}"
                                 fileName="${sys:log4j.dir}/thread-${threadLookup:threadName}.log"
                                 filePattern="${sys:log4j.dir}/thread-${threadLookup:threadName}-%i.log.gz">
                            <PatternLayout pattern="${logMsgPattern}"/>
                            <Policies>
                                <SizeBasedTriggeringPolicy size="100 MB" />
                            </Policies>
                    </RollingFile>
                </Route>
            </Routes>
        </Routing>

        <!-- Config for other appenders snipped -->

    </Appenders>

    <Loggers>
        <!-- Config for other loggers snipped -->
        <Root level="${sys:log4j.console.threshold}">
            <AppenderRef ref="rootOut" level="trace" />
            <AppenderRef ref="rootErr" level="error" />
            <AppenderRef ref="console" level="${sys:log4j.console.threshold}" />
            <AppenderRef ref="routing" level="trace" />
        </Root>
    </Loggers>

</Configuration>

但是,当我启动我的应用程序时,它只会在我的日志目录中创建一个名为 thread-${threadLookup(无扩展名)的附加文件。它也永远不会在 ThreadLookup.java.

中遇到任何断点

如何用log4j2注册插件(我用的是版本2.2,我也试过2.3)?请注意,我正在使用 spring-framework 4.1.7 项目,如果有帮助的话;我也为项目使用 maven,但我只是用它来解决依赖关系,我通过 ant 脚本构建项目。

更新

当我通过 ant 构建脚本时,我确实得到了一个 Log4j2Plugins.dat,它出现在我的 classpath (-cp resources:bin) 中,但它似乎没有效果服务器上生成的日志结果:

$ find bin/META-INF/ -type f
bin/META-INF/org/apache/logging/log4j/core/config/plugins/Log4j2Plugins.dat

$ cat bin/META-INF/org/apache/logging/log4j/core/config/plugins/Log4j2Plugins.dat
lookup
      threadlookupog4j2.plugins.ThreadLookup
                                            threadLookup

$ vi bin/META-INF/org/apache/logging/log4j/core/config/plugins/Log4j2Plugins.dat
^A^Flookup^A^Lthreadlookup^[log4j2.plugins.ThreadLookup^LthreadLookup

$ find logs -type f -name "thread-*"
logs/thread-${threadLookup:threadName}.log
logs/thread-${threadLookup:threadName}-1.log.gz</pre>

谢谢

我最终发现问题是我的 Plugin name 不能是驼峰式。

我在 private static void mergeByName(final Map<String, PluginType<?>> newPlugins, final List<PluginType<?>> plugins) 中的 line 169 上通过 PluginManager.javaLog4j2 - 2.3)进行调试,我发现我具有以下属性进入 newPlugins.put(key, pluginType);

  • 键:threadlookup,
  • pluginType: PluginType [pluginClass=class log4j2.plugins.ThreadLookup, key=threadlookup, elementName=threadLookup, isObjectPrintable=false, isDeferChildren==false, 类别=查找]

看到之后,我将 log4j2.xml 配置中的 Routing appender 修改为以下内容(无需更改 Plugin class 中实现的注释StrLookup) 并且有效:

    <Routing name="routing">
        <Routes pattern="$${threadlookup:threadName}">
            <Route>
                <RollingFile name="RollingFile-${threadlookup:threadName}"
                             fileName="${sys:log4j.dir}/thread-${threadlookup:threadName}.log"
                             filePattern="${sys:log4j.dir}/thread-${threadlookup:threadName}-%i.log.gz">
                        <PatternLayout pattern="${logMsgPattern}"/>
                        <Policies>
                            <SizeBasedTriggeringPolicy size="100 MB" />
                        </Policies>
                </RollingFile>
            </Route>
        </Routes>
    </Routing>

希望这可以帮助其他人,因为我不得不花几天时间来解决这个问题,而且我在为 Log4j2 审查的任何文档或问题中都没有发现这一点。

谢谢!