'How do I create a log4j logger that encodes output?

I have a java.util.logger that looks like this:

public class EncodedLogger {
    private static java.util.logging.Formatter createEncodedLoggerFormatter() {
        return new Formatter() {
            @Override public String format(LogRecord record) {
                return org.apache.commons.text.StringEscapeUtils.escapeJava(formatMessage(record));
            }
        };
    }
 
 
    public static Logger getLogger(){
        ConsoleHandler handler = new ConsoleHandler();
        handler.setFormatter(createSanitizedLoggerFormatter());
 
        Logger logger = java.util.logging.Logger.getAnonymousLogger();
        logger.addHandler(handler);
        return logger;
    }
}

The problem is I don't want to use the java util logger, I want to use log4j. I can't find a way to hack the formatter or override the methods of a logger. Any advice?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source