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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With