简体   繁体   中英

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). I'm using the (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 :

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.

[ 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? 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.

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 . But when it displays anything it shows where it is invoked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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