Search code examples
javaspringloggingspring-bootlogback

Format the logs using logback


I'm developping an application spring-boot. I use logback for logs side. I need to format the logs like this format.

aaa-mm-dd HH:mm:ss ## level ## TheNameOfMyApplication ## typeOfLogs ## class  ## message

this is a snippet of my file logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
        
        <Pattern>
            %d{yyyy-MM-dd HH:mm:ss} ## %-5level## TheNameofMyApplication ## %logger{36}##%msg%n
        </Pattern>
        </layout>
    </appender>

    <logger name="org.springframework.web" level="info" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>

    <logger name="com.myapp" level="info" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>

    <root level="error">
        <appender-ref ref="STDOUT" />
    </root>

</configuration>

What can I do to pass in the logger.info() parameter, for example, the type of my logs. I have three types:

  • technical, application and other

Best regards


Solution

  • You could use MDC (Mapped Diagnostic Context), using the %X specifier within the PatternLayout. Your pattern should look like:

    <Pattern>
        %d{yyyy-MM-dd HH:mm:ss} ## %-5level%X{nameofapplication} %logger{36}##%msg%n
    </Pattern>
    

    And then, your code:

     MDC.put("nameofapplication", "technical");
    

    Have a look to the documentation: LOGBack - Mapped Diagnostic Context


    For slf4j/logback, in order to set a MDC default value, when the entry has not been specified, you need to use the separator :- like:

    %{variable:-default value}
    

    So, your pattern should be:

    <Pattern>
        %d{yyyy-MM-dd HH:mm:ss} ## %-5level%X{nameofapplication:-technical} %logger{36}##%msg%n
    </Pattern>