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.
Your problem is that:
is a
static
method which returns originalLogger
class.MyLogger
is ignored. The easiest approach is to wrap originally returnedLogger
class in the spirit of decorator pattern:In order to use
MyLogger
decorator you must wrap original logger with it:Consider wrapping it in custom factory.
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
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:
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
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.