简体   繁体   中英

How to modify a log4j2 message before it is logged?

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.

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM