9

I'm using Logback and I need to avoid CRLF(Carriage Return and Line Feed) when I log a user parameter.
I tried to add my class, which extends ClassicConverter, on the static map PatternLayout.defaultConverterMap but It didn't work.

Thank you,

bedrin
  • 4,458
  • 32
  • 53
user3551863
  • 301
  • 3
  • 7

3 Answers3

3

You should create a custom layout as described in logback documentation

Custom layout:

package com.foo.bar;

import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.ILoggingEvent;

public class RemoveCRLFLayout extends PatternLayout {

    @Override
    public String doLayout(ILoggingEvent event) {
        return super.doLayout(event).replaceAll("(\\r|\\n)", "");
    }

}

Logback configuration:

<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
    <layout class="com.foo.bar.RemoveCRLFLayout">
        <pattern>%d %t %-5p %logger{16} - %m%n</pattern>
    </layout>
</encoder>
bedrin
  • 4,458
  • 32
  • 53
2

For a quick solution we used a %replace expression in our pattern, to replace line feed and carraige returns found in the message.

Note this example is using a Spring Boot property to set the pattern, but you can use %replace in your Logback config file the same way.

logging:
  pattern:
    console: "%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %replace(%msg){'\n|\r', '_'}%n"

(A custom converter would have been my first choice, but I had trouble getting it to work with Spring Boot and Spring Cloud Config. If you want to learn more about that approach, search the logback docs for conversionRule.)

Bampfer
  • 2,120
  • 16
  • 25
0

ch.qos.logback.core.CoreConstants;

public static final String LINE_SEPARATOR = System.getProperty("line.separator");

ch.qos.logback.classic.pattern.LineSeparatorConverter:

public String convert(ILoggingEvent event) {
    return CoreConstants.LINE_SEPARATOR;
}

package ch.qos.logback.classic.PatternLayout:

    defaultConverterMap.put("n", LineSeparatorConverter.class.getName());

So the proper way to ensure fixed line ending is the property line.separator.

The same implementation is for java.lang.System.lineSeparator():

lineSeparator = props.getProperty("line.separator");
gavenkoa
  • 45,285
  • 19
  • 251
  • 303