Search code examples
logback

Show logs only from one class using logback


I am trying to display logs into console as well as file however in file i want only certain logs that will be displayed from one particular class and i am not sure how to do this. Below is my logback.xml

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

<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>{ "date_time":"%date", "thread":"[%thread]", "log_level":"%-5level", "class_name":"%logger{0}", "log_message":"%msg" }%n</pattern>
        </encoder>
    </appender>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file> test.txt </file>
    <append>false</append>
    <encoder>
        <pattern>{ "date_time":"%date", "thread":"[%thread]", "log_level":"%-5level", "class_name":"%logger{0}", "log_message":"%msg" }%n</pattern>
    </encoder>
  </appender>

  <root level="info">
    <appender-ref ref="FILE" />
    <appender-ref ref="STDOUT" />
  </root>

</configuration>

Solution

  • Just declare a logger for your "one particular class" and then associate that logger with your FILE appender.

    For example:

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>test.log</file>
        <encoder>
            <pattern>{ "date_time":"%date", "thread":"[%thread]", "log_level":"%-5level", "class_name":"%logger{0}", "log_message":"%msg" }%n</pattern>
        </encoder>
    </appender>
    
    <logger name="your.particular.Class">
        <appender-ref ref="FILE" />
    </logger>
    
    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>
    

    This will ensure that any log events emitted by your.particular.Class are only directed to the FILE appender and all other logs will be directed only to the STDOUT appender.