Wednesday, June 22, 2011

How to hide some data in log4j log you consider to be secured

Once we get the requirement saying the customer does not want some data gets transfered to the log file since it looks secure for them. We even should have the capability of choosing whether to show such data in logs. The quick way to address the requirement is to override one method in PatternLayout class. This will look like:

import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;

public class SecureLayout extends PatternLayout{

                static String pattern;
                
                public static void setPattern(String pattern){
                                SecureLayout.pattern = pattern;
                }

                @Override
                public String format(LoggingEvent event) {
                                String string = super.format(event);
                                return pattern == null ?  string : string.replaceAll(pattern, "NotForYourEyes");
                }

}

Such the way will allow us to set which data we consider to be secured from any place of the code. So you should only place the class under the classpath and use the following construction in log4j.xml

    <appender name="FILE" class="org.apache.log4j.RollingFileAppender">
        <param name="File" value="logfile.log"/>
        <param name="Append" value="true"/>
        <param name="MaxFileSize" value="1000KB"/>
        <param name="MaxBackupIndex" value="1000"/>
        <layout class="some.package.SecureLayout">
            <param name="ConversionPattern" value="%-5p [%d{ISO8601}] - %m%n"/>
        </layout>
    </appender>

However such solution of described engineering problem has some drawback. It means we are not capable to hide the data in exception description as exceptions are handled in another way. However that problem can be solved by introducing the changes in Exception class.