An alternative approach could be to create a customized LogEventFactory
. A LogEventFactory
is used to generate LogEvents. Applications may replace the standard LogEventFactory
by setting the value of the system property Log4jLogEventFactory
to the name of the custom LogEventFactory class.
The method that will be called to create a instance of LogEvent
is as follows:
LogEvent createEvent(String loggerName,
org.apache.logging.log4j.Marker marker,
String fqcn,
org.apache.logging.log4j.Level level,
org.apache.logging.log4j.message.Message data,
List<Property> properties,
Throwable t)
and DefaultLogEventFactory
is the basic implementation for log4j. In your case you could extend the basic implementation and escape the message after which you call the default implementation. It would become something like this:
public class MyCustomLogEventFactory extends DefaultLogEventFactory {
/**
* Creates a log event.
*
* @param loggerName The name of the Logger.
* @param marker An optional Marker.
* @param fqcn The fully qualified class name of the caller.
* @param level The event Level.
* @param data The Message.
* @param properties Properties to be added to the log event.
* @param t An optional Throwable.
* @return The LogEvent.
*/
@Override
public LogEvent createEvent(final String loggerName, final Marker marker,
final String fqcn, final Level level, final Message data,
final List<Property> properties, final Throwable t) {
super.createEvent(loggerName, marker, fqcn, level, StringEscapeUtils.escapeJava(data != null ? data.toString() : null), properties, t);
}
}