LOG4J: Modify logged message using custom appender

前端 未结 4 594
一生所求
一生所求 2020-12-01 06:41

For security reasons, I need to look at every logged message in my app and possibly modify it before it goes to the log file. I figured I could write a custom appender (exte

4条回答
  •  鱼传尺愫
    2020-12-01 07:20

    Thats how I did since I am working with an older version of log4j

    Instead of customizing appender, I customized the layout and referred that layout in whichever Appender i needed this feature

    public class LogValidatorLayout extends PatternLayout {
    
        public LogValidatorLayout() {
            super();
        }
    
        public LogValidatorLayout(String pattern) {
            super(pattern);
        }
    
        @Override
        public String format(LoggingEvent event) {
    
            // only process String type messages
            if (event.getMessage() != null && event.getMessage() instanceof String) {
    
                String message = event.getMessage().toString();
                message = StringUtils.trim("Some custom text --->>"+message);
    
                // earlier versions of log4j don't provide any way to update messages,
                // so use reflections to do this
                try {
                    Field field = LoggingEvent.class.getDeclaredField("message");
                    field.setAccessible(true);
                    field.set(event, message);
                } catch (Exception e) {
                    // Dont log it as it will lead to infinite loop. Simply print the trace
                    e.printStackTrace();
                }
    
            }
    
            return super.format(event);
        }
    
    }
    

    And in your log4j.properties or xml, register this Layout

    log4j.appender.STDOUT.layout=a.b.c.package.LogValidatorLayout
    

提交回复
热议问题