logback configure and use

Brief introduction

logback is another open source log4j log component by the founder of the design. The current is divided into three modules:

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

  • logback-classic is a modified version of log4j. Further logback-classic full implementation SLF4J API, so that you can easily be changed into other logging system, such as log4j or JDK14 Logging.

  • logback-access access module integrated with Servlet containers supplied by Http access log function.

Configuration

Configuration pom.xml

logback need logback-Core , logback-Classic , SLF4J-API , logback Access- four dependent. Logback-classic which already contains logback-core and slf4j-api-dependent, due to the dependence of Maven transitive, so we just import logback-classic and logback-access can rely on.

    <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 step

1. Find logback-test.xml file in the class path.

2. If not found, it looks logback.groovy file in the classpath.

3. If not found, it looks logback.xml file in the classpath.

4. If not, try using ServiceLoader load the next classpath com.qos.logback.classic.spi.Configurator implementation class META-INF \ services \ ch.qos.logback.classic.spi.Configurator configuration file (Configurator file content to achieve fully qualified class name of the class).

5. If still not found, it will load the default configuration, log output to the console by default, that is, the use of BasicConfigurator, BasicConfigurator is the implementation class 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">
  <!-- 自定义属性,通过${}访问 -->
  <property name="filePath" value="/logs/" />
    
  <!-- 输出到控制台 -->
  <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>
  
  <!-- 输出到文件 -->
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <!-- 文件路径 -->
    <file>${filePath}app.log</file>
    <!-- 日志输出格式化 -->
    <encoder>
        <pattern>%date [%level] [%thread] %logger{80} [%file : %line] %msg%n</pattern>
    </encoder>
    
    <!-- 滚动策略 -->
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <!-- 每日滚动 -->
      <fileNamePattern>${filePath}app.log%d{yyyy-MM-dd}.log</fileNamePattern>
     
      <!-- 将30天的日志总大小限制在3GB内  -->
      <maxHistory>30</maxHistory>
      <totalSizeCap>3GB</totalSizeCap>
    </rollingPolicy>
  </appender> 
  
  <!-- 基于尺寸和时间的滚动策略 -->
  <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>
       <!-- 每个日志文件最多100MB,保存60天的历史记录,总大小不超过20GB -->
       <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属性指定包名或者完全限定类名 -->
  <logger name="service.OtherService" level="DEBUG">
        <appender-ref ref="ROLLING" />
  </logger>

  <!-- 根logger -->
  <root level="DEBUG">
    <!-- 配置输出源 -->
    <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) {
        //根据logback.xml中配置的日志级别,TRACE级别的日志将不会输出,只会输出DEBUG及以上级别的日志。
        //TRACE < DEBUG < INFO <  WARN < ERROR
        logger.trace("---------------trace---------------");
        logger.debug("---------------debug---------------");
        logger.info("---------------info---------------");
        logger.warn("---------------warn---------------");
        logger.error("---------------error---------------");
    }
}

General Tips

1. placeholders

        logger.debug("我是" + name + ",我今年" + age + "岁,很高兴认识你!");//普通方式
        logger.debug("我是{},我今年{}岁,很高兴认识你!", name, age);//占位符方式(推荐)

When debug logging is disabled, the normal way, the parameters will still be constructed mosaic, while in the placeholder, the parameter will not be constructed mosaic.

2 should be used when using the API slf4j logback instead of using an API (log facade dependent, rather than relying on specific logging implementation, to facilitate replacement of other logging framework)

3. Automatic re-load the configuration file

will scan property element is set to true, logback regularly scan profile, if the profile has changed, it will automatically reload the configuration file. Default scan once per minute, may be provided to specify properties scanPeriod scanning interval.

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

Guess you like

Origin www.cnblogs.com/seve/p/11271076.html