LOG4J同一类中的多个Logger [英] LOG4J Multiple Loggers in same class

查看:637
本文介绍了LOG4J同一类中的多个Logger的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有log4j日志记录的Java项目.它使用滚动文件追加器和多个记录器来记录文件. 我想添加一个DBappender并有一个单独的记录器,该记录器仅写入该附加器,其他记录器均未向其发送消息.我需要说一个类,有两个记录器,一类写入fileAppender,一类写入dbAppender.如果可以的话,这是可能的配置吗?

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?

谢谢

推荐答案

可以在一个类中使用两个Logger.

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")
}

dbLogger软件包的配置:

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

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

(未经测试.) 在这种情况下,dbLogger也会记录到mainlog附加程序.如果不合适,您可以使用 mainlog(和其他)附加程序中的自定义过滤器,用于过滤dbLogger的消息.另一种解决方案是为dbLogger使用完全不同的前缀:

(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配置:

<root> 
</root> 

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

请注意,如果将相同的参数传递给getLogger()方法,则将获得相同的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.

这篇关于LOG4J同一类中的多个Logger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆