log4j2 extending Logger class

2019-08-13 11:14发布

问题:

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

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?

回答1:

I can understand why you might have wanted to do this with Log4j 1.x, but I cannot figure out why you would want to do this with log4j 2. The best place to do this is in a Layout, but most already do this.



回答2:

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.

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 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.