Possible to use different log4j appenders for different methods?

元气小坏坏 提交于 2019-12-11 13:08:58

问题


I have a log4j configuration file and it uses a ConsoleAppender with a specific layout.

I use logger.info("some text"); in several places in my java code.

Is it possible to create another appender with a different layout in the configuration file and use the specific appender wherever I choose in the code?


回答1:


Is it possible to create another appender with a different layout in the configuration file and use the specific appender wherever I choose in the code?

Yes you can create different appender with a different layout and create different categories for each appender.

use the category name to get the logger instead of appender name.


Sample: (log4j.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="stdout1" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%.4t] %-5p %c{1} - %m%n" />
        </layout>
    </appender>

    <appender name="stdout2" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d [%.4t] %-5p %c{1} - %m%n" />
        </layout>
    </appender>

    <category name="category1">
        <priority value="INFO" />
        <appender-ref ref="stdout1" />
    </category>

    <category name="category2">
        <priority value="DEBUG" />
        <appender-ref ref="stdout2" />
    </category>

</log4j:configuration>

Java Code: (get the logger based on category name)

org.apache.log4j.Logger.getLogger("category1").warn("debug msg for stdout1 appender");
org.apache.log4j.Logger.getLogger("category2").info("info msg for stdout2 appender");

Output:

[main] WARN  category1 - warn msg for stdout1 appender
2014-05-09 02:46:29,216 [main] INFO  category2 - info msg for stdout2 appender


来源:https://stackoverflow.com/questions/23551207/possible-to-use-different-log4j-appenders-for-different-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!