Friday, June 16, 2017

Create new log file with Logback for each run of a Java program

SLF4J and Logback are becoming de facto standard for Java logging framework, so here is a useful snippet to generate new log file everytime Java program runns.
I use this simple configuration mostly for standalone Java apps, like POCs or small utility tools.
There are more advanced appenders in Logback but I find this one simple yet effective.

Few advantages of such config:
  • each run generates new log file
  • file name contains run date and time up to milisecond precission
  • all logs are put in separate directory, which can be added to .gitignore
  • http log messages don't pollute main log file
  • you can manipilate http log level with CLI switch (-DHTTP_LOG_LEVEL=debug)

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
 <timestamp key="runDateTime" datePattern="" />

 <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
  <layout class="ch.qos.logback.classic.PatternLayout">
   <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</Pattern>
 <appender name="FILE" class="ch.qos.logback.core.FileAppender">
   <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
 <appender name="FILEHTTP" class="ch.qos.logback.core.FileAppender">
   <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>

 <logger name="org.apache.http.wire" level="${HTTP_LOG_LEVEL:-WARN}" additivity="false">
  <appender-ref ref="FILEHTTP" />

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

What to remember:
  • Apache HttpClient 4.x uses Commons Logging, so you need jcl-over-slf4j bridge
  • you can limit to log only http headers by using "org.apache.http.headers"instead
  • order of dependencies matter - other slf4j implementation might take precedence over Logback
  • for httpclient 3.x you need to use httpclient.wire.content and httpclient.wire.header respectively
  • logging HttpClient traffic will generate large log files

No comments:

Post a Comment

Please be polite in comments.