log4j2扩展Logger类 [英] log4j2 extending Logger class

查看:575
本文介绍了log4j2扩展Logger类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Log4j 1.7迁移到Log4j2.4 在1.7中,我通过扩展org.apache.log4j.Logger并使用扩展的debug/error/fatal方法来创建AppLogger类. 例如

I am trying to migrate from Log4j 1.7 to Log4j2.4 In 1.7, I as creating AppLogger class by extending org.apache.log4j.Logger and using extending debug/error/fatal Methods e.g.,

public void error(Object message) {
   Object error = message;

 if (message instanceof Exception) {
    Exception e = (Exception) message;
    StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        error = sw.toString();
    }

 super.error(error);
}

但是在Log4j 2.x中,我无法扩展org.apache.logging.log4j.Logger类; 实现此目标的最佳方法是什么?

But in Log4j 2.x, I am not able to extend the class org.apache.logging.log4j.Logger; What is the Best way to achieve this?

推荐答案

正如Ralph所指出的,Log4j2具有非常丰富的功能集,如果翻阅文档,您通常会发现,使用内置布局

As Ralph pointed out, Log4j2 has a very rich set of functionality, and if you go over the documentation, you often find that you can achieve your goals using the built-in layouts, lookups, filters and other features.

编写自定义查询仅需几行代码并为您提供了一个强大的日志子系统,可以将其用于许多目的.

Writing a custom lookup only takes a few lines of code and gives you a powerful hook into the logging subsystem which you can use for many purposes.

如果您出于某些原因确实想要扩展Logger,请注意某些布局要求Log4j遍历stacktrace以报告从记录器中调用了代码中的哪个类和行.这种机制有点复杂,通常我建议您创建一个Logger包装器,而不是对其进行扩展. (最好是委托而不是子类化.)

If you really want to extend Logger for whatever reason, be aware that some layouts require Log4j to walk the stacktrace to report which class and line in your code from the logger was called from. This mechanism is a bit complex and in general I would recommend you create a Logger wrapper instead of extending it. (Prefer delegation to subclassing.)

Log4j有一个工具可以简化您的工作:

Log4j has a tool to make this easy for you: the Custom Logger Generator tool documented in the Custom Log Levels page. Try this and see if it gives you what you need.

这篇关于log4j2扩展Logger类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆