Ignore formatting in XML Logback file

Viewed 150

I'm using the Rolling File Appender in Logback with a very basic Encoder Pattern to log in JSON. The app is written in Java. I know there are a few Logback JSON packages out there for Java, but I decided not to use them so I didn't have to introduce any new dependencies in the code.

I've got the following appender working. It spits out logs in a JSON format that Filebeat and Logstash can read.

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>/opt/tomcat/logs/LOG.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <!-- rollover daily -->
      <fileNamePattern>/opt/tomcat/logs/LOG.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
      <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
        <!-- or whenever the file size reaches 100MB -->
        <maxFileSize>200MB</maxFileSize>
      </timeBasedFileNamingAndTriggeringPolicy>
      <maxHistory>30</maxHistory>
      <cleanHistoryOnStart>true</cleanHistoryOnStart>
    </rollingPolicy>
    <encoder>
      <pattern>
{"@timestamp": "%d{ISO8601}", "date": "%d{dd-MM-yy}", "thread": "%thread", "level": "%-5level", "className": "%logger{36}", "message": "%replace(%replace(%msg){'\n','\u2028'}){'\t',' '} %replace(%replace(%ex){'\n','\u2028'}){'\t',' '}" }%nopex%n
      </pattern>
    </encoder>
  </appender>

As you can see the indentation of this line {"@timestamp": "%d{ISO8601}",.... is off (if I indent it, it gets indented in the log file, itself), and the line is way too long for any Checkstyle validation (and readability). I'd much rather compose it like this:

<encoder>
  <pattern>
    {
      "@timestamp": "%d{ISO8601}", 
      "date": "%d{dd-MM-yy}", 
      ...
    }%nopex%n
  </pattern>
</encoder>

Any thoughts on how I can get XML and/or Logback to ignore the formatting of this pattern and just spit out the text?

1 Answers

The below creates a property that holds the pattern, so perhaps it would allow you to format it as you want:

Example:

  <property name="ENCODER_PATTERN"
          value="%d{yyyy-MM-dd  HH:mm:ss.SSS} [%thread] %-5level %logger{80} - %msg%n" />


  <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${ENCODER_PATTERN}</pattern>
  </encoder>
Related