Manipulating log messages in logback over MessageConverter

Osman ÇETİN
1 min readNov 14, 2022

--

After log4j vulnerability, logging is getting more big attention. Logging is one of the main application parts and to perform it we generally rely on framework/library ability.

Alright, what can we develop else to be more secure on logging mechanism? One of them is adding new extended Message converter to logback. Being do that, we will have ability to manipulate every message logging through logback.

First step is extending new class from logback MessageConverter like below. This class is the class that we can change log messages, you can use own manipulating way or you can use additional libraries like ESAPI.

import org.apache.commons.text.StringEscapeUtils;

import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

public class LogMessageConverter extends MessageConverter{

@Override
public String convert(ILoggingEvent event) {

String secureMsg = super.convert(event).replace("\n", "_").replace( "\r", "_" ).replace("script", "_script_");

secureMsg = StringEscapeUtils.escapeHtml4(secureMsg);

// secureMsg = ESAPI.encoder().encodeForHTML(secureMsg);
// secureMsg = ESAPI.encoder().encodeForJavaScript(secureMsg);
// secureMsg = ESAPI.encoder().encodeForXML(secureMsg);

return secureMsg;
}
}

After doing that, you need to define this extended class to logback as second step.

Please add below definition logback configuration file.

<conversionRule conversionWord="secureMsg" converterClass="com.web.app.security.LogMessageConverter"/>

And know you are ave ability use “secureMsg” keyword instead of “msg” in your appender like below.

<appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOGS}/logging.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) >>- %secureMsg %n</Pattern>
</encoder>
</appender>

That’s it, there is no more changes required, all of the logs have been already developed in your application has been effected.

For the result, let’s look at the consequence of development.

log.info("script");

Console:

_script_

--

--

No responses yet