How can I direct log4j output so that different log levels go to different appenders?

时间秒杀一切 提交于 2019-12-04 08:38:01

问题


Is it possible to have "debug" and "info" output written to the console while the "info" output is only written to some log file? For example, given this logging:

LOG.debug(fileContent);
LOG.info(fileLength);

What does a corresponding log4j.xml look like?


回答1:


Ok, I've got it now:

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        ...
    </appender>

    <appender name="otherAppender"
              class="org.apache.log4j.FileAppender FileAppender">
       <param name="Threshold" value="INFO"/>
        ...
    </appender>

    <root>
        <priority     value="debug" />
        <appender-ref ref="console" />
        <appender-ref ref="otherAppender" />
    </root>
</log4j:configuration>

Thanks for your help!




回答2:


That is definitely possible. The configuration would look something like this (not checked for syntactic correctness):

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        ...
    </appender>

    <appender name="otherAppender"
              class="org.apache.log4j.FileAppender FileAppender">
        ...
    </appender>

    <logger name="com.mycompany.mypackage.MyClass">
        <level        value="info"/>
        <appender-ref ref="otherAppender" />
    </logger>

    <root>
        <priority     value="debug" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>

All debug and info messages go to the console appender. Info messages go to otherAppender.




回答3:


Go to this page for some examples.

It's as simple as adding two different appenders to your program, one appender for each type of logging you want to do.




回答4:


With the configuration from Eddie I can only get the "info" output for MyClass. But what I would like to have is that the "info" output of MyClass goes to a file AND the "debug" output of MyClass goes to console.




回答5:


Do as rwwilden suggested but remove this part:

<logger name="com.mycompany.mypackage.MyClass">
    <level value="info"/>
    <appender-ref ref="otherAppender" />
</logger>

And add <param name="Threshold" value="INFO"/> under the otherAppender.



来源:https://stackoverflow.com/questions/751431/how-can-i-direct-log4j-output-so-that-different-log-levels-go-to-different-appen

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