简体   繁体   English

SLF4J / LOG4J:在日志实用程序类中使用提供的记录器

[英]SLF4J / LOG4J: Use provided logger in log-utility class

For some complex logging tasks I have a Utility class which builds the log-entries (some with multiple lines). 对于某些复杂的日志记录任务,我有一个Utility类来构建日志条目(有些包含多行)。 I'm using the (log4j) ConversionPattern: 我正在使用(log4j)ConversionPattern:

<param name="ConversionPattern" value="[%5p] %C{1}-%L: %m%n" />

here is a simplified example: 这是一个简化的示例:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UtilityClass
{
  private final static Logger logger = LoggerFactory.getLogger(UtilityClass.class);

  public static void test(Logger mainLogger, Class<?> c)
  {
    logger.info("Log from UtilClass with UtilClass-Logger");
    mainLogger.info("Log from UtilClass with MainClass-Logger");

    Logger log = LoggerFactory.getLogger(c);
    log.info("buildLogger");
  }
}

Now the MainClass : 现在是MainClass

private final static Logger logger = LoggerFactory.getLogger(MainClass.class);
public void testLogger()
{   
  logger.info("Log from MainClass");
  UtilityClass.test(logger,this.getClass());
}

I'm getting this output and wondering why the third line comes from the UtilityClass. 我正在获得此输出,并且想知道为什么第三行来自UtilityClass。

[ INFO] MainClass-28: Log from MainClass
[ INFO] UtilityClass.test-12: Log from UtilClass with UtilClass-Logger
[ INFO] UtilityClass.test-13: Log from UtilClass with MainClass-Logger     <--------
[ INFO] UtilityClass.test-16: buildLogger

Well, of course that's exactly the place where the logger is invoked. 好吧,当然,这正是记录器被调用的地方。 But is it possible to pass information of the calling class (here the MainClass) to the log entry even if the logger is invoked in the UtilityClass? 但是,即使在UtilityClass中调用了记录器,也可以将调用类的信息(这里是MainClass)传递给日志条目吗? I want to get something like this: 我想得到这样的东西:

[ INFO] MainClass-28: Log from MainClass
[ INFO] UtilityClass.test-12: Log from UtilClass with UtilClass-Logger
[ INFO] MainClass-29: Log from UtilClass with MainClass-Logger     <--------
[ INFO] MainClass-29: buildLogger                                  <--------

Because the logger is showing you where it is invoked. 因为记录器正在向您显示调用它的位置。 When you instantiate one with: 当您使用以下方法实例化一个时:

LoggerFactory.getLogger(xxx);

xxx is just the name of the logger that you can configure in xml/property file. xxx只是您可以在xml /属性文件中配置的记录器的名称

For example: 例如:

Config : 配置

log4j.logger.ONE = INFO
log4j.logger.TWO = DEBUG.

Code : 代码

a = LoggerFactory.getLogger("ONE");
b = LoggerFactory.getLogger("TWO");

So the a.debug is not appearing in logs, because you configured logging level to INFO . 因此,因为a.debug日志记录级别配置为INFO ,所以a.debug不会出现在日志中。 But when it displays anything it shows where it is invoked. 但是,当它显示任何内容时,它会显示在何处调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM