【问题标题】:Java Logging: Log4j Version2.x: show the method of an end-client caller (not an intermediate logging helper method)Java 日志记录:Log4j Version2.x:显示终端客户端调用者的方法(不是中间日志记录助手方法)
【发布时间】:2016-02-12 10:59:24
【问题描述】:

以下 3 篇文章提供了有关如何使用中间日志记录助手并仍然让底层记录器从客户端的方法向该日志记录助手报告的答案(而不是将日志记录助手方法报告为源):

但似乎只为Log4j 1.2 提供答案,它提供了现已失效的:

 Category.log(String callerFQCN, Priority level, Object message, Throwable t). 

Logger in the log4J 2.5 API 似乎没有明显的等价物。

任何人都可以提供与直接使用 Log4J 2.x 兼容的答案吗?

【问题讨论】:

    标签: java logging log4j


    【解决方案1】:

    对于 Log4j2,答案完全是通过使用 Log4j2 手册中Example Usage of a Generated Logger Wrapper 下所述的记录器包装器来提供的。可以简单地生成(使用那里说明的 org.apache.logging.log4j.core.tools.Generate$ExtendedLogger 工具)具有单个 STUB 级别的记录器包装器,然后对其进行调整以创建自定义日志记录方法,模仿 logIfEnabled 的使用(FQCN、LEVEL、Marker、message、Throwable)- 可能忽略 STUB 级别并使用常规级别 - 然后如果需要,删除或注释掉 STUB 级别及其方法)。为此,FormattedMessage 可能会有所帮助。

    例子:

    java -cp log4j-core-2.5.jar org.apache.logging.log4j.core.tools.Generate\$ExtendedLogger com.mycomp.ExtLogger STUB=350 > com/mycomp/ExtLogger.java
    

    然后适配生成的类(大部分支持方法省略):

    public final class ExtLogger extends ExtendedLoggerWrapper {
        ...
        private final ExtendedLoggerWrapper logger;
    
        private static final String FQCN = ExtLogger.class.getName();
        private static final Level STUB = Level.forName("STUB", 350);
        //Delete this afterwards if level not used.
    
        private ExtLogger(final Logger logger) {
            super((AbstractLogger) logger, logger.getName(), logger.getMessageFactory());
            this.logger = this;
        }
    
        /**
         * Returns a custom Logger with the name of the calling class.
         * 
         * @return The custom Logger for the calling class.
         */
        public static ExtLogger create() {
            final Logger wrapped = LogManager.getLogger();
            return new ExtLogger(wrapped);
        }
    
        /**
         * Returns a custom Logger using the fully qualified name of the Class as
         * the Logger name.
         * 
         * @param loggerName The Class whose name should be used as the Logger name.
         *            If null it will default to the calling class.
         * @return The custom Logger.
         */
        public static ExtLogger create(final Class<?> loggerName) {
            final Logger wrapped = LogManager.getLogger(loggerName);
            return new ExtLogger(wrapped);
        }
    
        ...
    
        /**
         * Logs a message object with the {@code STUB} level.
         * 
         * @param message the message object to log.
         */
        public void stub(final String message) {
            logger.logIfEnabled(FQCN, STUB, null, message, (Throwable) null);
        }
    
    
        /**
         * Example: Adapt with custom formatting.
         * Here DEBUG level is used just as an example.
         *
         * @param name
         * @param value 
         */
        public void echo(final String name, Object value) {
            Message m = new FormattedMessage("echo: %s(%s)",name,value);
            logger.logIfEnabled(FQCN, Level.DEBUG, null, m, (Throwable) null);
        }
        ...
    }
    

    然后在客户端类中,它现在将通过记录器的辅助方法“代表”该客户端正确记录,在本例中为格式化示例 echo(name,value):

    public class TestLog4j {
    
        private static final ExtLogger extLogger = ExtLogger.create(TestLog4j.class);
    
        public static void elseWhere() {
            extLogger.echo("aVariableName", 4);
        }
    
        public static void main(String[] args) {
                extLogger.echo("aStringVariableName","from main");
                elseWhere();
        }
    }
    

    简单的图案布局:

      <PatternLayout pattern=" %-5level [%C{1}::%M(%L)] %logger{36} - %msg%n"/>
    

    输出:

     DEBUG [TestLog4j::main(63)] testlogging.TestLog4j - echo: aStringVariableName(from main)
     DEBUG [TestLog4j::elseWhere(42)] testlogging.TestLog4j - echo: aVariableName(4)
    

    一旦掌握了将 logger.logIfEnabled(FQCN,...) 与 FQCN(log4j 在堆栈跟踪中搜索)一起使用的窍门,您可能希望删除或注释掉 stub(..) 方法和 STUB 级别,如果您不使用附加级别。

    【讨论】:

      【解决方案2】:

      如果您正在构建一个新系统,请坚持使用 Webel 的答案。

      如果你有一个正在迁移到 log4j2 的现有系统,你可能仍然应该运行 generate 方法(但我在下面包含了一个最小的工作类),你可以添加这个函数,它提供了旧的 1.2 callerFQCN 做事方式(有点):

      public void log(Class ignoreClassFQCN, Level level, Marker marker, String msg, Throwable throwable){    
          logger.logIfEnabled(ignoreClassFQCN.getName(), level, marker, msg, throwable);
      }
      

      然后,从您的 现有 日志包装类中,您可以执行以下操作:

      // inside ThisClass.java, denoting an old logger such as one that used log4j 1.2 with the callerFQCN parameter, or just an old logger that's naive and custom built.
      private static final MyLog4j2WrapperClass newLogger = MyLog4j2WrapperClass.create();
      
      public static void debug(String message) {
          // basic example
          newLogger.log(ThisClass.class, Level.DEBUG, null, message, null);
      }
      
      public static void logFailure(String message) {
          // example of using a custom log level
          newLogger.log(ThisClass.class, MyLog4j2WrapperClass.FAILURE, null, message, null);
      }
      

      我碰巧删除了一堆我没有使用的其他生成函数,因为我计划为设计不佳的(自定义)日志记录系统做一个简单的填充程序。我删除了一堆我不打算使用的 create() 方法。所以这里是一个工人阶级(值得分享的部分):

      public final class MyLog4j2WrapperClass extends ExtendedLoggerWrapper {
          private static final long serialVersionUID = 1L;
          private final ExtendedLoggerWrapper logger;
      
          private static final String FQCN = MyLog4j2WrapperClass.class.getName();
          public static final Level FAILURE = Level.forName("FAILURE", 150);
      
          public void log(Class ignoreClass, Level level, Marker marker, String msg, Throwable throwable){
              logger.logIfEnabled(ignoreClass.getName(), level, marker, msg, throwable);
          }
      
          private MyLog4j2WrapperClass(final Logger logger) {
              super((AbstractLogger) logger, logger.getName(), logger.getMessageFactory());
              this.logger = this;
          }
      
          /**
           * Returns a custom Logger with the name of the calling class.
           *
           * @return The custom Logger for the calling class.
           */
          public static MyLog4j2WrapperClass create() {
              final Logger wrapped = LogManager.getLogger();
              return new MyLog4j2WrapperClass(wrapped);
          }
      

      我应该注意,我认为这是一个 shim —— 它可以让您轻松过关,但我强烈建议您在安装 shim 后继续远离旧的日志记录系统。这将使您无需立即完成完全迁移即可进行更多增量代码更改。

      【讨论】:

        猜你喜欢
        • 2016-05-22
        • 1970-01-01
        • 2011-06-17
        • 2013-11-11
        • 2013-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多