I need to do some enhancements to Log4j2 so that the message gets altered prior to logging. Now, I know that I can write a custom converter and define the pattern so that it uses my custom converter, however, this will not work for me.
The scenario is that, depending on the class that calls the logger, I must do some changes or not. And this needs to be done dynamically from the code.
Let's assume I have this interface:
public interface LogMessageAlter {
String alterMessage(Message message);
}
Now, I have multiple classes that implement this interface: "RemoveIpAlter" and "RemoveEndpointAlter". How can I specify to the converter what alterers to use when doing the conversion?
One approach would be to write my own logger and overwrite the logMessage method:
public class MyLogger extends Logger {
public void logMessage(..., Message message) {
alterList.forEach(alter -> alter.altermessage(message));
super(..., message)
}
}
However, I can't figure out how to tell Log4J to instanciate my custom logger when Logmanager.getLogger() is called instead of using the default Logger class.
Other ideas are also appreciated.
Later edit: I know that using LogManager.getLogger("aName")
can be used to return a custom logger, but this does not solve my problem because I want a per-class list of modifiers. I want to be able to do something like this:
LogManager.getLogger(MyClass.class, modifierList);
, or in a wrapper
MyLogger logger = Logmanager.getLogger(MyClass.class);
logger.setModifiers(modifierList);