Search code examples
javalogginglogbackslf4j

Logback to log different messages to two files


I am using logback/slf4j to do my logging. I want to parse my log file to analyze some data, so instead of parsing a great big file (mostly consisting of debug statements) I want to have two logger instances which each log to a separate file; one for analytics and one for all purpose logging. Does anyone know if this is possible with Logback, or any other logger for that matter?


Solution

  • It's very possible to do something like this in logback. Here's an example configuration:

    <?xml version="1.0"?>
    <configuration>
        <appender name="FILE" class="ch.qos.logback.core.FileAppender">
            <file>logfile.log</file>
            <append>true</append>
            <encoder>
                <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
            </encoder>
        </appender>
        <appender name="ANALYTICS-FILE" class="ch.qos.logback.core.FileAppender">
            <file>analytics.log</file>
            <append>true</append>
            <encoder>
                <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
            </encoder>
        </appender>
        <!-- additivity=false ensures analytics data only goes to the analytics log -->
        <logger name="analytics" level="DEBUG" additivity="false">
            <appender-ref ref="ANALYTICS-FILE"/>
        </logger>
        <root>
            <appender-ref ref="FILE"/>
        </root>
    </configuration>
    

    Then you'd setup two separate loggers, one for everything and one to log analytics data like so:

    Logger analytics = LoggerFactory.getLogger("analytics");