user3576299
user3576299

Reputation: 15

Is there a good way to use Slf4j to log certain event to a separate log file?

I am using Slf4j for logging in my Java service, but for certain type of events, I want to create a separate log file for it.

Is it possible to use Slf4j to implement that?

Upvotes: 1

Views: 861

Answers (1)

sfThomas
sfThomas

Reputation: 1955

Slf4j is just an abstraction that helps you interface with various logging frameworks - you will need to select a logging framework too. Below is an example with logback - but if you prefer other frameworks (JUL, log4j2), the same concept works with those as well.

What you need to do is to log your special events under a specific logger:

Logger logger = LoggerFactory.getLogger("my.special.events");
logger.info("Oh my! Something has happened!");

Then set up logback (or the framework of your choice) to send the events coming via this logger to another destination (another appender) too:

<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%msg%n</pattern>
    </encoder>
  </appender>

  <appender name="SPECIAL" class="ch.qos.logback.core.FileAppender">
    <file>specialEvents.log</file>  
    <encoder>
      <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
    </encoder>
  </appender>

  <logger name="my.special.events">
    <appender-ref ref="SPECIAL" />
  </logger>  

  <root level="debug">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

This will send your special events to both STDOUT and to the separate file. If you only need these events in the file, set the additivity to false, as described in the docs.

Upvotes: 1

Related Questions