how to create MyLogger?

2019-04-21 00:50发布

问题:

I use log4j for logging. And I would like to modify methods: warn(..), error(..). I would like to modify message in this methods. So, is there any way, how to create my own logger?

public class MyLogger extends Logger {

protected MyLogger(String name) {
    super(name);
}

@Override
public void error(Object message) {
    message = "test - " + message;

    super.error(message);
}

}

And in class call:

private static final Logger logger = MyLogger.getLogger(TestClass.class);

logger.error("error message");

But it, do not work. Could you help me? Thanks.

回答1:

Your problem is that:

MyLogger.getLogger(TestClass.class)

is a static method which returns original Logger class. MyLogger is ignored. The easiest approach is to wrap originally returned Logger class in the spirit of decorator pattern:

public class MyLogger extends Logger {
    final Logger target;
    protected MyLogger(Logger target) {
        this.target = target;
    }

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

    //...

}

In order to use MyLogger decorator you must wrap original logger with it:

private static final Logger logger = 
  new MyLogger(Logger.getLogger(TestClass.class));

Consider wrapping it in custom factory.



回答2:

You should never create your own Logger. I have seen many bad reason to create one, but never a good one. If you want to add some contextual information in the log statements, you can use the NDC/MDC feature of Log4J.

http://wiki.apache.org/logging-log4j/NDCvsMDC



回答3:

Don't modify the logger - a logger is a just a convenient way to send log messages to the logging framework. The processing of the messages happens in the appenders.

So you have two options:

  1. You can tell the main appender (which is attached to the root logger), to process these messages for you. Look here: LOG4J: Modify logged message using custom appender

  2. Create a new appender which delegates to an existing appender. That way, you can attach this special appender to only some loggers.

    Just implement AppenderAttachable<E> in your appender. Then you can use <appender-ref .../> in it's configuration.