RockyB
RockyB

Reputation: 59

Write specific logs to a log file spring-boot/slf4j

I am able to write console logs to rotating log files using this method here:

https://www.codejava.net/frameworks/spring-boot/logback-rolling-files-example

But my requirement is to write only specific logs to the log files instead of whole console log. For example, i need to write only the json messages(i can print them on console using log.info(message) which is supported by slf4j) being received by Kafka listener to the log files and nothing more. How can i achieve this in my spring-boot app? Is this not possible with slf4j logback?

Upvotes: 0

Views: 1589

Answers (1)

allkenang
allkenang

Reputation: 1645

Specify the appender-ref in your logger element.

So something like this in your logger XML configuration file:

<appender name="console" class="org.apache.log4j.ConsoleAppender">
    <param name="Target" value="System.out"/>
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
    </layout>
</appender>

<appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
    <param name="append" value="false"/>
    <param name="maxFileSize" value="1GB"/>
    <param name="maxBackupIndex" value="2"/>
    <param name="file" value="/tmp/bd.log"/>
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
    </layout>
</appender>

Then in the same config file, add a appender reference to the log file that you are interested in

<logger name="com.example.ClassWithJsonMessage" additivity="false">
    <level value="debug"/>
    <appender-ref ref="bdfile"/>
</logger>

Upvotes: 2

Related Questions