views:

304

answers:

2

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?

+1  A: 

Its possible with log4j, so I assume that logback has only improved on that.

The classes should each declare their own static logger as a default convention, then in the configuration you would declare multiple categories and appenders.
The categories are used for refining which log statements from which classes should be sent through to the appenders, and the appenders apply more filter criteria e.g. log-level and then write to their specific media (file, database, email, jms etc.)

crowne
+3  A: 

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>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</Pattern>
        </layout>
    </appender>
    <appender name="ANALYTICS-FILE" class="ch.qos.logback.core.FileAppender">
        <File>analytics.log</File>
        <Append>true</Append>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</Pattern>
        </layout>
    </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 log = LoggerFactory.getLogger("analytics");
ig0774