'How can I create a logger that extends log4j2?
I am trying to migrate from log4j 1 to log4j 2.
My current logger extends Logger which is imported by
org.apache.log4j.Logger.
Logger is a class which doesn't exist in log4j2.
In Log4j2 we have
org.apache.logging.log4j.Logger which is an interface and in order to implement it, I'll have to implement lots of methods of this interface, which I don't want to.
Other option is to extend org.apache.logging.log4j.LogManager which is a class but have entire different methods set and doesn't really return or create a Logger type class.
I mean that if i'll write
public final class MyLogger extends LogManager {
I'll limit my logger to LogManager instance instead of Logger instance.
My current code is:
import org.apache.log4j.Logger;
/**
* The Class MyLogger.
*/
public final class MyLogger extends Logger {
/** The logger instance. */
private Logger loggerInstance = null;
/** The MyLogger logger. */
private static MyLogger myLogger = null;
/**
* Instantiates a MyLogger logger.
*/
private MyLogger() {
super("MyLogger");
}
/**
* Gets the logger.
*
* @param clazz - The Class
* @return the logger
*/
public static MyLogger getLogger(Class clazz) {
myLogger = new MyLogger();
myLogger.setLoggerInstance(Logger.getLogger(clazz));
return myLogger;
}
I've managed to re-write
private MyLogger() {
super("MyLogger");
}
to
private MyLogger() {
getLogger("MyLogger");
}
which calls the getLogger method inside the extended class LogManager.
but I don't know how to re-write
public static MyLogger getLogger(Class clazz) {
myLogger = new MyLogger();
myLogger.setLoggerInstance(Logger.getLogger(clazz));
return myLogger;
}
and other methods that I wrote to override:
/**
* Warn.
*
* @param message the message
*/
@Override
public void warn(Object message) {
loggerInstance.warn(message);
}
/**
* Gets the logger instance.
*
* @return the logger instance
*/
public Logger getLoggerInstance() {
return loggerInstance;
}
/**
* Sets the logger instance.
*
* @param loggerInstance the new logger instance
*/
public void setLoggerInstance(Logger loggerInstance) {
this.loggerInstance = loggerInstance;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
