5

I'm new to SLF4J and Logback and I'm trying to log every request and response of API following this link. Here's the configuration

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%requestURL | status code: %statusCode | bytes: %bytesSent | elapsed time: %elapsedTime | request-log: %magenta(%requestContent) | response-log: %cyan(%responseContent)</pattern>
        </encoder>
    </appender>
    <appender-ref ref="STDOUT"/>
</configuration>

Currently it's printing:

GET /api/request HTTP/1.1 | status code: 200 | bytes: 599 | elapsed time: 2630 | request-log:  | response-log {"key1":"field1","key2":"field2"}

And I want to log something like:

{
    "url": "GET /api/request HTTP/1.1",
    "status": 200,
    "elapsed_time": 2630 ,
    "response": {
        "key1":"value1",
        "key2":"value2"
    }
}
  • if you are using spring boot here is the best example https://www.mkyong.com/spring-boot/spring-boot-slf4j-logging-example/ – Ganesh Gudghe Aug 09 '19 at 06:08
  • try this https://www.baeldung.com/java-log-json-output – MyTwoCents Aug 09 '19 at 06:35
  • Thanks for the replies. As I understand, the examples above are triggering logger by calling the logger methods. In my case, I'm using FilterRegistrationBean, therefore logger should be working automatically on each request. – Bat-Erdene Zorigtbaatar Aug 09 '19 at 07:02

1 Answers1

5

This would work:

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="net.logstash.logback.encoder.LogstashEncoder">
        <jsonFactoryDecorator class="JsonLogDecorator"/>
        <fieldNames>
            <timestamp>timeStamp</timestamp>
            <message>message</message>
            <logger>logger</logger>
            <thread>thread</thread>
            <level>level</level>
            <levelValue>[ignore]</levelValue>
            <version>[ignore]</version>
            <stackTrace>stackTrace</stackTrace>
        </fieldNames>
        <includeMdcKeyName>mdcKeyToInclude</includeMdcKeyName>
    </encoder>
</appender>

JsonLogDecorator is custom class that implements JsonFactoryDecorator.

Prashant Pandey
  • 4,332
  • 3
  • 26
  • 44