Tuesday, July 21, 2015

Basic Configuration for logback

Here is the basic logback configuration for these goals:

  • One log file per day.
  • Keep max n days’ log. Over old log file will be automatically deleted (n=30  in this demo)
  • Max size of every log file x  (x=200MB in this demo)

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
  <configuration>
  <!-- define where to store the log file -->  
  <property name="LOG_HOME" value="." />  
    
  <!-- to screen --> 
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <!-- screen output pattern -->
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level [%F:%L] - %msg %n</pattern>
    </encoder>
  </appender>

  <!-- to file -->
  <appender name="FILE"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <!-- log file name -->
      <FileNamePattern>${LOG_HOME}/itf.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
      <timeBasedFileNamingAndTriggeringPolicy
        class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
        <!-- or whenever the file size reaches 200MB -->
        <maxFileSize>200MB</maxFileSize>
      </timeBasedFileNamingAndTriggeringPolicy>
      <!-- keep 30 days' worth of history -->
      <maxHistory>30</maxHistory>
    </rollingPolicy>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
      <!-- log file pattern:
        %d{...} : date and time in format
        %thread : thread name
        %-5level: log level, left aligned, 5 words length
        [%F:%L] : file name and line number
        %msg    :message
        %n      : newline -->
      <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level [%F:%L] - %msg%n</pattern>
    </encoder>
  </appender>

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

put the logback.xml file in the resources folder. For example in a maven project, put logback.xml in src/main/resources/

0 comments:

Post a Comment

Powered by Blogger.

About The Author

My Photo
Has been a senior software developer, project manager for 10+ years. Dedicate himself to Alcatel-Lucent and China Telecom for delivering software solutions.

Pages

Unordered List