【问题标题】:Logging controller/service using Log4j ( Centralized logging )使用 Log4j 记录控制器/服务(集中式记录)
【发布时间】:2012-08-15 09:14:52
【问题描述】:

我不想使用这样的东西:

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

每次我想记录一些东西。

我尝试实现一个日志服务,其方法如下:

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

这允许我根据发送者的类获取 Logger 实例,但它隐藏了日志源类的方法和行。

我知道 AOP 或 Slf4j 等替代方案。第一个不是我想要的,第二个引入了类似于第一行代码的东西:

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

所以,我关心的不是隐藏 Log4j 依赖项,而是统一整个应用程序的日志调用,如下所示:

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

有什么方法可以实现吗?

【问题讨论】:

    标签: java logging log4j


    【解决方案1】:

    好的,看来至少有一种方法可以解决这个问题:

    例如有 LoggingService 和 LoggingController。第一个直接使用 Log4j,第二个只是服务和整个应用程序之间的一层。

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

    因此,在这种情况下,您允许用户使用:

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

    这样使用:

    1. 用户对底层的日志记录功能一无所知
    2. 如果您不需要或环境不允许,您始终可以提供虚拟记录器。
    3. 日志记录功能在整个应用程序中统一
    4. 类名和代码行在日志中正确显示。
    5. 您不能使用 Log4j 最有用的功能之一 - 按包/类名过滤。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 2012-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多