LOG4J Multiple Loggers in same class

与世无争的帅哥 提交于 2019-12-05 02:07:47

问题


I have a java project that has a log4j logging. It uses a rolling file appender and multiple loggers to log to a file. I want to add a DBappender and have a seperate logger that only writes to this appender, with none of the other loggers sending messages to it. I need, say one class to have two loggers, one writing to the fileAppender and one writing to the dbAppender. Is this possible, if so what is the configuration for it?

Thanks


回答1:


It's possible to use two Loggers in one class.

First idea: get the two loggers with different names:

package com.mycompany.apackage.MyClass;

public class MyClass {
    private static final logger = Logger.getLogger(Myclass.class)
    private static final dbLogger = Logger.
        getLogger(Myclass.class.getName() + ".dblogger")
}

Config for the package of the dbLogger:

<root> 
    <appender-ref ref="mainlog" /> 
</root> 

<logger name="com.mycompany.apackage.MyClass.dblogger">
    <appender-ref ref="dbappender" />
</logger>

(Not tested.) In that case the dbLogger also logs to the mainlog appender. If it's not appropriate you could use a custom filter in the mainlog (and other) appenders which filters out the messages of the dbLogger. Another solution is using a completely different prefix for the dbLogger:

    private static final logger = Logger.getLogger(Myclass.class)
    private static final dbLogger = Logger.
        getLogger("dblogger." + Myclass.class.getName())

Log4j config:

<root> 
</root> 

<logger name="com.mycompany">
    <appender-ref ref="mainlog" />
</logger>
<logger name="dblogger.com.mycompany">
    <appender-ref ref="dbappender" />
</logger>

Note that if you pass the same parameter to the getLogger() method you will get same Logger object, so you have to use different names.



来源:https://stackoverflow.com/questions/7659348/log4j-multiple-loggers-in-same-class

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