简体   繁体   中英

slf4j logger singleton issue

I want to do logging using slf4j . I write my own logger class

public class GlobalLogger {
   private static final Logger logger = LoggerFactory.getLogger(GlobalLogger.class);
   public static void logApplicationLog(String message) {
     logger.info("[" + APPLICATION_LOG + "]" + message);
   }
}

I use pattern layout in log4j so that in log %C display class as GlobalLogger but I want that %C should display the calling class. How do I do that with condition that object of logger should be singleton in whole application?

Write a wrapper over the logger class , which will act as a singleton class. Like :

public class Logger{

private static Logger logger;    
private Logger(){
}
public synchronized static Logger getLogger()
    {
        if (logger!= null)
            return logger;
        return logger=LoggerFactory.getLogger(GlobalLogger.class);
    }

}

If you want a shorthand for creating a logger and putting a message to it:

public class GlobalLogger {

   public static void logApplicationLog( String message, Class source ) {
     LoggerFactory.getLogger(source).info("[" + APPLICATION_LOG + "]" + message);
   }

}

I don't know of a possibility to inject a source on a "per message" basis, though there may be one.

Note: I recommend using a static Logger instance in each class that is supposed to log something rather than the code I gave above. You could even change your IDE's template for creating new clases to already include that for you.

EDIT

I see you want to put a static portion to create "Categories" (as to your comments above).

Then why don't you LoggerFactory.getLogger(APPLICATION_LOG) and create appenders for each of the Categories with a static text added in the pattern? Or do you have to be able to change logLevels by packages?

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