Java: How to log raw JSON as JSON and avoid escaping during logging with logback / slf4j

后端 未结 7 2215
攒了一身酷
攒了一身酷 2021-02-05 13:09

I\'m using SLF4J with Logback in a JAX-RS application... I want to log to JSON in such a way that my message is not encoded again but printed raw into the logfile:

At t

相关标签:
7条回答
  • 2021-02-05 13:57

    Just came over this myself and found an article with a few recommandations on logging.

    If you use maven put this dependency into pom.xml

    <dependency>
        <groupId>net.logstash.logback</groupId>
        <artifactId>logstash-logback-encoder</artifactId>
        <version>3.4</version>
    </dependency>
    

    And put something like this into logback.xml

    <configuration>
        <property name="PROJECT_ID" value="example"/>
        <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <File>logs/${PROJECT_ID}.json</File>
            <encoder class="net.logstash.logback.encoder.LogstashEncoder"/>
            <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
                <maxIndex>1</maxIndex>
                <FileNamePattern>logs/${PROJECT_ID}.json.%i</FileNamePattern>
            </rollingPolicy>
            <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
                <MaxFileSize>1MB</MaxFileSize>
            </triggeringPolicy>
        </appender>
        <logger name="eu.kielczewski" additivity="false" level="INFO">
            <appender-ref ref="file"/>
        </logger>
        <root level="WARN">
            <appender-ref ref="file"/>
        </root>
    </configuration>
    

    This creates example.json file under logs/. The file is rolled once when it reaches 1MB in size.

    LOGGER.debug(append("object", someObject), "log message");
    
    0 讨论(0)
提交回复
热议问题