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
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