1

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);
Petre Popescu
  • 1,950
  • 3
  • 24
  • 38
  • Hello. Can you check this ? : https://stackoverflow.com/questions/6023950/wrap-log4j-or-create-custom-logger Someone wrote : Logger log = new Logger(MyClass.class); This might be useful to you. – AntiqTech Feb 08 '21 at 08:08
  • https://issues.apache.org/jira/browse/LOG4J2-519 Yep, now I get what you want. Hope this helps – aran Feb 08 '21 at 08:32
  • 1
    @aran partially it does help. It is a push in the right direction (I hope). Thanks – Petre Popescu Feb 08 '21 at 08:52
  • 1
    @aran The thread you provided, even though it did not solve my problem directly, gave me an idea. What I will try is to define my own custom Message. In this message, I can store the needed modifiers as a list. Then, in the converter, i check if it is my message and apply them to the formattedMessage(). – Petre Popescu Feb 08 '21 at 09:45
  • Yeah, I finally got your point, sorry for misleading the question at first. Your idea, if well implemented, could be a feature request for log4j2 (even thou they are full of them). It's a pretty clever idea, indeed. – aran Feb 08 '21 at 09:48
  • 1
    Thanks. Now comes the implementation part. Thanks for the kick in the right direction :D – Petre Popescu Feb 08 '21 at 10:12

0 Answers0