如何将Log4j与带有动态文件名的附加程序一起使用?

时间:2020-05-06 08:36:01

标签: java log4j log4j2

我想多次使用log4j-Appender,但文件名不同:

Appender:

<RollingFile name="MODULE" fileName="log/module-${ModuleName}.log" append="true" filePattern="log/module-${ModuleName}-%d{yyyy-MM-dd}_%i.log" >
    <PatternLayout pattern="%d{yyyy/MM/dd-HH:mm:ss} %-5p %C:%M:%L ~ %m%n"/>
    <Policies>
        <OnStartupTriggeringPolicy />
        <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
        <SizeBasedTriggeringPolicy size="100MB"/>
    </Policies>
    <DefaultRolloverStrategy max="10"/>
</RollingFile>

记录器:

<Logger name="MOD1" level="debug">
    <Properties>
        <Property name="ModuleName">MOD1</Property>
    </Properties>
    <appender-ref ref="MODULE"/>
</Logger>
<Logger name="MOD2" level="error">
    <Properties>
        <Property name="ModuleName">MOD2</Property>
    </Properties>
    <appender-ref ref="MODULE"/>
</Logger>

但这不起作用。如何将变量从记录仪传递到Appender? 最后我要2个文件

/log/module-MOD1.log <- Debug messages from MOD1
/log/module-MOD2.log <- Error messages from MOD2

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

只需添加另外一个Appender并分别将LoggerAppender连接起来即可。

例如:

...
<RollingFile name="MODULE1" fileName="./log/module1-${ModuleName}.log" append="true" filePattern="./log/module1-${ModuleName}-%d{yyyy-MM-dd}_%i.log" >
    <PatternLayout pattern="%d{yyyy/MM/dd-HH:mm:ss} %-5p %C:%M:%L ~ %m%n"/>
    <Policies>
        <OnStartupTriggeringPolicy />
        <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
        <SizeBasedTriggeringPolicy size="100MB"/>
    </Policies>
    <DefaultRolloverStrategy max="10"/>
</RollingFile>

<RollingFile name="MODULE2" fileName="./log/module2-${ModuleName}.log" append="true" filePattern="./log/module2-${ModuleName}-%d{yyyy-MM-dd}_%i.log" >
    <PatternLayout pattern="%d{yyyy/MM/dd-HH:mm:ss} %-5p %C:%M:%L ~ %m%n"/>
    <Policies>
        <OnStartupTriggeringPolicy />
        <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
        <SizeBasedTriggeringPolicy size="100MB"/>
    </Policies>
    <DefaultRolloverStrategy max="10"/>
</RollingFile>
...

...
<Logger name="com.foo.bar.ClassName1" level="debug">
    <Properties>
        <Property name="ModuleName">MOD1</Property>
    </Properties>
    <appender-ref ref="MODULE1"/>
</Logger>
<Logger name="com.foo.bar.ClassName2" level="error">
    <Properties>
        <Property name="ModuleName">MOD2</Property>
    </Properties>
    <appender-ref ref="MODULE2"/>
</Logger>
...

有一个同样的问题,所以我也回答了。因此,请访问here