在 log4j2 pkg 中继承记录器接口的方法

inherit method to logger interface in log4j2 pkg

我有办法

     import org.apache.logging.log4j.Logger;
     public class SendEmail
     {  
        Logger log = LogManager.getRootLogger();
        public static String getStackTrace(final Throwable throwable)
        {
           final StringWriter sw = new StringWriter();
           final PrintWriter pw = new PrintWriter(sw, true);
           throwable.printStackTrace(pw);
           return sw.getBuffer().toString();
        } 
public static void main(String[] args)
    {
        try
        {
           //Some Code
        }
        catch (Exception e)
        {
          log.error(getStackTrace(e));
        }
    }
   }

并且我想通过继承将 getStackTrace() 方法添加到 Logger(注意:Logger 是接口而不是 Class)所以我可以通过日志对象调用它所以我可以替换 log.error(getStackTrace(e)) ;通过 log.error(log.getStackTrace(e)) ; 有帮助吗?

简单的方法是使用 logger.error("message", exception),但如果您想要自定义方法,则需要创建自己的 class 并将原始记录器保留在其中。有error和debug方法,如果需要其他方法需要自己创建(比如warn)。

public class MyLogger {
    final Logger target;

    public MyLogger(Logger target) {
        this.target = target;
    }

    public void error(Object message) {
        target.error(message);
    }

    public void debug(Object message) {
        target.debug(message);
    }

    //...

    public String getStackTrace(final Throwable throwable) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        throwable.printStackTrace(pw);
        return sw.getBuffer().toString();
    }
}

另一个class:

private static final MyLogger logger = new MyLogger(LogManager.getRootLogger());

public void someMethod() {
    try {
        //
    }
    catch (Exception e) {
        logger.error(logger.getStackTrace(e));
    }
}