1

I'm trying to avoid the possibility of log forging in our java based webservice application that uses log4j. Since we do not use any html based log viewer, we do not need to encode HTML contents in the log messages. I just want to avoid new line characters. So if there are any \n or \r in the log message, print them as spaces instead of actually doing a new line.

I prefer not to use any extra jars. For example, using ESAPI requires all the classes to be changed from Logger.getLogger(ClassName1.class); to ESAPI.getLogger(ClassName1.class), and whereever you print logs needs to be changed from logger.info("message") to logger.info(Logger.EVENT_SUCCESS, "message") which we do NOT want to do for all the existing codebase. Also using the ESAPI adds extra content to each log entries which is unnecessary.

Is there any log4j configurations to make it replace \n or \r into spaces for all the things it logs? If not, is there any simple wrappers on top of log4j that does this functionality?

yaloner
  • 715
  • 2
  • 6
  • 19
user3366706
  • 1,529
  • 3
  • 31
  • 54

1 Answers1

0

Sorry I am new to stackoverflow bear my noob answer

It is better to create your own custom PatternLayout and use it in the log4j.xml inside PatternLayout tag.

for example:

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 add this class in log4j.xml and this answer is taken from another page

LOG4J: Modify logged message using custom appender