logback configuration and use

Posted by peter_anderson on Tue, 30 Jul 2019 16:08:36 +0200

brief introduction

logback is another open source log component designed by the founder of log4j. Currently, it is divided into three modules:

  • logback-core is the basic module of the other two modules.

  • Logback-classic is an improved version of log4j. In addition, logback-classic fully implements the SLF4J API, so that you can easily replace it with other logging systems, such as log4j or JDK14 Logging.

  • logback-access access module integrates with Servlet container to provide access to logs through Http.

To configure

Configure pom.xml

Logback requires four dependencies: logback-core, logback-classic, slf4j-api and logback-access. Logback-classic already contains logback-core and slf4j-api dependencies. Because of the transitivity of Maven dependencies, we only need to import logback-classic and logback-access dependencies.

    <dependencies>
        <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
          <version>1.3.0-alpha4</version>
        </dependency>
        <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-access</artifactId>
          <version>1.3.0-alpha4</version>
        </dependency>
    </dependencies>

Initialization steps

1. Find the logback-test.xml file in the classpath.

2. If not, look for the logback.groovy file in the classpath.

3. If not, look for the logback.xml file in the classpath.

4. If not found, try to use Service Loader to load the com.qos.logback.classic.spi.Configurator implementation class configured in the META-INFservicesch.qos.logback.classic.spi.Configurator file under the classpath (the content of the Configurator file fully qualifies the class name for the implementation class).

5. If it is still not found, the default configuration will be loaded, and the log will be output to the console by default, that is, using Basic Configurator, which is also the implementation class of the com.qos.logback.classic.spi.Configurator interface.

public class BasicConfigurator extends ContextAwareBase implements Configurator {

    public BasicConfigurator() {
    }

    public void configure(LoggerContext lc) {
        addInfo("Setting up default configuration.");
        
        ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<ILoggingEvent>();
        ca.setContext(lc);
        ca.setName("console");
        LayoutWrappingEncoder<ILoggingEvent> encoder = new LayoutWrappingEncoder<ILoggingEvent>();
        encoder.setContext(lc);
        
 
        // same as 
        // PatternLayout layout = new PatternLayout();
        // layout.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
        TTLLLayout layout = new TTLLLayout();
 
        layout.setContext(lc);
        layout.start();
        encoder.setLayout(layout);
        
        ca.setEncoder(encoder);
        ca.start();
        
        Logger rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
        rootLogger.addAppender(ca);
    }
}

Use logback.xml

<configuration scan="true" scanPeriod="30 seconds">
  <!-- Customize properties by ${}Visit -->
  <property name="filePath" value="/logs/" />
    
  <!-- Output to console -->
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} %msg%n</pattern>
    </encoder>
  </appender>
  
  <!-- output to a file -->
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <!-- File path -->
    <file>${filePath}app.log</file>
    <!-- Log output formatting -->
    <encoder>
        <pattern>%date [%level] [%thread] %logger{80} [%file : %line] %msg%n</pattern>
    </encoder>
    
    <!-- Rolling strategy -->
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <!-- Scroll daily -->
      <fileNamePattern>${filePath}app.log%d{yyyy-MM-dd}.log</fileNamePattern>
     
      <!-- Limit the total log size for 30 days to 3 GB within  -->
      <maxHistory>30</maxHistory>
      <totalSizeCap>3GB</totalSizeCap>
    </rollingPolicy>
  </appender> 
  
  <!-- Rolling strategy based on size and time -->
  <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${filePath}other.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
      <fileNamePattern>${filePath}other.log%d{yyyy-MM-dd}%i.log</fileNamePattern>
       <!-- Up to 100 log files per log file MB,Keep a 60-day historical record of a total size of no more than 20 GB -->
       <maxFileSize>1KB</maxFileSize>    
       <maxHistory>60</maxHistory>
       <totalSizeCap>20GB</totalSizeCap>
    </rollingPolicy>
    <encoder>
        <pattern>%date [%level] [%thread] %logger{80} [%file : %line] %msg%n</pattern>
    </encoder>
  </appender>
  
  <!-- name Property specifies the package name or fully qualified class name -->
  <logger name="service.OtherService" level="DEBUG">
        <appender-ref ref="ROLLING" />
  </logger>

  <!-- root logger -->
  <root level="DEBUG">
    <!-- Configure the output source -->
    <appender-ref ref="STDOUT" />
    <appender-ref ref="FILE" />
  </root>
</configuration>

Test:

public class HelloService {
    private final static Logger logger = LoggerFactory.getLogger(HelloService.class);
    
    public static void main(String[] args) {
        //According to the log level configured in logback.xml, the TRACE level log will not output, only the DEBUG level log and above.
        //TRACE < DEBUG < INFO <  WARN < ERROR
        logger.trace("---------------trace---------------");
        logger.debug("---------------debug---------------");
        logger.info("---------------info---------------");
        logger.warn("---------------warn---------------");
        logger.error("---------------error---------------");
    }
}

Common Skills

1. Use placeholders

        logger.debug("I am" + name + ",I am this year" + age + "Years old. Nice to meet you!");//Ordinary way
        logger.debug("I am{},I am this year{}Years old. Nice to meet you!", name, age);//Placeholder mode (recommended)

When debug log is disabled, parameters will still be structured mosaic in normal mode, but in placeholder mode, parameters will not be structured mosaic.

2. The API of slf4j should be used instead of the API of logback (depending on the log facade rather than the specific log implementation to facilitate the replacement of other log frameworks)

3. Auto-reload configuration files

Setting the scan attribute of the element to true, logback scans the configuration file regularly, and automatically reloads the configuration file if the configuration file changes. By default, scanPeriod property can be set to specify the scan interval.

<configuration scan="true" scanPeriod="30 seconds" > 
  ...
</configuration> 

Topics: PHP xml log4j Maven Attribute