Log4j - Have multiple appenders write to the same file with one that always logs

后端 未结 4 1229
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 21:43

I have a log4j appender defined like:

log4j.logger.com.example = DEBUG, filelog

log4j.appender.filelog=org.apache.log4j.DailyRollingFileAppender
log4j.appen         


        
相关标签:
4条回答
  • 2020-12-09 22:06

    I don't think log4j really supports two appenders writing to the same file because of synchronization issues. Your best bet would be, if possible, to make a switch to slf4j using Logback as your backend logging system since Logback is log4j's successor and also supports multiple appenders writing to one file. Check out FileAppender and it's prudent mode.

    Update: from your description, it seems you should also check out markers. You only need one logger instance, and you can get more fine grained control using markers, because with them you basically say "this log statement has a special purpose, and has to be logged using an appropriate appender". You can also check log appender additivity, which is usually used when you use two or more appenders for one log statement.

    0 讨论(0)
  • 2020-12-09 22:23

    I got this to work by using AsyncAppenders. I had my main appender which specified a file to log to, and had my other appenders refer to it.

    e.g.

    <appender name="top" class="org.apache.log4j.rolling.RollingFileAppender">
        <param name="file" value="myLog.log" />
    </appender>
    
    <appender name="other" class="org.apache.log4j.AsyncAppender">
        <appender-ref ref="top" />
    </appender>
    
    <logger name="com.example.MyCLass">
        <appender-ref ref="other" />
    </logger>
    

    You can add other filters, or whatever to the other appenders. As far as I can tell with my own app, the logs seem to roll, and the appender filters work as expected.

    0 讨论(0)
  • 2020-12-09 22:25

    Yes. You can "workaround" to have 2 appenders writing to the same file.

    Checkout this code + example:

    Any questions welcome.

    0 讨论(0)
  • 2020-12-09 22:27

    As far as I'm aware, the instantiation of loggers with a package & class identifier is just a convention. You are free to create multiple logger instances in any class and give them any identifier.

    Log alwaysLogger = LogFactory.getLog("a.b.c.ALWAYS");
    Log sometimesLogger = LogFactory.getLog("a.b.c.SOMETIMES");
    

    As for writing to the same file, I have not tried it but it should be possible, at least from a single thread. You may need to write your own appender rather than relying on one of the default ones.

    0 讨论(0)
提交回复
热议问题