1

I would like to be able to have a method execute for every log message that will allow me to dynamically modify that message before it is logged. I know there are Filters that allow me to indicate whether a message should be logged or not, but I don't want to stop the message from being logged, I just want to modify it before it is logged. How can I go about doing this?

Note: I asked this question about log4j2 but I am open to other popular Java logging frameworks as well.

Hmmmmm
  • 778
  • 9
  • 20

2 Answers2

4

Don't forget the factory method :)

    @PluginFactory
    public static MarkerInjectorRewritePolicy createPolicy() {
        return new MarkerInjectorRewritePolicy();
    }

here's a working example on my github account: https://github.com/sercasti/Log4j-RewriteAppender/

sercasti
  • 550
  • 3
  • 7
3

You can implement your own appender.

http://logging.apache.org/log4j/2.x/manual/appenders.html#RewriteAppender

Just extend the current appender you are using and add the behaviour you need, or simply use the RewriteAppender

RewriteAppender The RewriteAppender allows the LogEvent to manipulated before it is processed by another Appender. This can be used to mask sensitive information such as passwords or to inject information into each event. The RewriteAppender must be configured with a RewritePolicy. The RewriteAppender should be configured after any Appenders it references to allow it to shut down properly.

sercasti
  • 550
  • 3
  • 7
  • I implemented a RewritePolicy but I am not registering it correctly. I tried to follow [this example](https://stackoverflow.com/questions/30247323/how-to-create-custom-rewritepolicy-in-log4j2) but ended up getting this error: "Unable to invoke factory method in class class...". Any idea how to register this RewritePolicy correctly? – Hmmmmm May 29 '17 at 22:29