简体   繁体   中英

Logging controller/service using Log4j ( Centralized logging )

I don't want to use something like this :

Logger.getLogger(MyClass.class).info("Info message");

each time I want to log something.

I've tried to implement a logging service that has methods like :

public void info(final Object aMessage, final Object aSender);

This allows me get Logger instance based on sender's class, but it hides the method and line of the log source class.

I know about alternatives like AOP or Slf4j. The first one is not exactly I want, the second one introduces something similar to the first line of code :

LoggerFactory.getLogger(HelloWorld.class).info("Info message");

So, my concern is not about hiding Log4j dependency, it's about unifying logging calls through the whole application, like this :

//loggingController instance was injected previously
loggingControler.info("Info message",this);

Is there any way to implement this ?

Ok, seems that there is at least one way to resolve the issue :

For example there are LoggingService and LoggingController. The first one works directly with Log4j, the second one is just a layer between service and the whole application.

public class LoggingService implements ILoggingService{

   //other methods here.

   @Override
   public void warn(final Object aMessage, final Object aSender, final Throwable aThrowable) {
       log(aMessage, aSender, Level.WARN, aThrowable);
   }


   private void log(final Object aMessage, final Object aSender, final Level aLevel, final Throwable aThrowable) {
       final String className = getClassNameBy(aSender);
       Logger.getLogger(className).log(className, aLevel, aMessage, aThrowable);
   }
}

public class LoggingController implement ILoggingController{
    //logging service is injected previously
    @Override
    public void warn(final Object aMessage, final Throwable aThrowable) {
        loggingService.warn(aMessage, this, aThrowable);
    }
}

So, in this case you allow the user to log something using :

loggingController.warn("A warning", null);

Using this way:

  1. User knows nothing about underlying logging functionality
  2. You always have the possibility to provide a dummy logger if you don't need it, or the environment doesn't allow it.
  3. The logging functionality is unified across the whole application
  4. The class name and code line are shown correctly in the log.
  5. You cannot use one of the most useful features of the Log4j - filtering by package/class name.

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