Java project log example: LogBack

Click below to follow me, and then click... "Set as star" in the upper right corner to receive updates as soon as possible~~~

LogBack and Log4j are both open source journal tool libraries. LogBack is an improved version of Log4j. It has more features than Log4j and also brings great performance improvements. LogBack officially recommends using it in conjunction with Slf4j, which can flexibly replace the underlying log framework.

Logback mainly consists of three modules:

  • logback-core

  • logback-classic

  • logback-access

Among them, logback-core provides the core functions of LogBack and is the basis of the other two components. The status and function of logback-classic are equivalent to Log4J. It is also considered an improved version of Log4J, and it implements the simple log facade SLF4J, so when you want to use it with SLF4J, you need to add logback-classic to the classpath; and logback- Access is mainly used as a module that interacts with Servlet containers, such as tomcat or jetty, to provide some functions related to HTTP access.

1

Logback usage examples

c12beb7204a15dec4144cf6d1d09c23d.png

1. Select the jar package

If you want to use Logback in a Java program, you need to rely on three jar packages, namely slf4j-api, logback-core, and logback-classic. Among them, slf4j-api is not part of Logback. It is recommended to use SLF4J in combination with Logback.

pom.xml:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>


<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-core</artifactId>
    <version>1.2.3</version>
</dependency>


<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>


<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-access</artifactId>
    <version>1.2.3</version>
</dependency>

2、logback.xml

Create logback.xml in the src root directory and modify the configuration accordingly according to your own needs. Its contents are as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!-- status用来指定log4j本身的打印日志的级别 -->
<!--monitorInterval:Log4j能够自动检测修改配置文件和重新配置本身,设置间隔秒数 -->
<configuration status="WARN" monitorInterval="30">
    <!--先定义所有的appender -->
    <appenders>
        <!--这个输出控制台的配置 -->
        <console name="Console" target="SYSTEM_OUT">
            <!--输出日志的格式 -->
            <PatternLayout
                pattern="[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] %l %logger{36} - %msg%n" />
        </console>


        <!--定义输出到指定位置的文件 -->
        <File name="log" fileName="/jpm/log4j2/logs/log.log" append="true">
            <PatternLayout
                pattern="[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] %l %logger{36} - %msg%n" />
        </File>


        <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
        <RollingFile name="RollingFileInfo" fileName="/jpm/log4j2/logs/info.log"
            filePattern="/jpm/log4j2/logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
            <!-- DENY,日志将立即被抛弃不再经过其他过滤器;NEUTRAL,有序列表里的下个过滤器过接着处理日志;ACCEPT,日志会被立即处理,不再经过剩余过滤器。-->
            <ThresholdFilter level="error" onMatch="DENY"
                onMismatch="ACCEPT" />
            <PatternLayout
                pattern="[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] %l %logger{36} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="100 MB" />
            </Policies>
            <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了30 -->
            <DefaultRolloverStrategy max="30" />
        </RollingFile>


        <RollingFile name="RollingFileError" fileName="/jpm/log4j2/logs/error.log"
            filePattern="/jpm/log4j2/logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="ERROR" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout
                pattern="[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] %l %logger{36} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="100 MB" />
            </Policies>
        </RollingFile>
    </appenders>


    <!--只有定义了logger并引入的appender,appender才会生效 -->
    <loggers>
        <!--过滤掉spring和mybatis的一些无用的DEBUG信息 -->
        <logger name="org.springframework" level="INFO"></logger>
        <logger name="org.mybatis" level="INFO"></logger>
        <root level="INFO">
            <appender-ref ref="Console" />
            <appender-ref ref="log" />
            <appender-ref ref="RollingFileInfo" />
            <appender-ref ref="RollingFileError" />
        </root>
    </loggers>
</configuration>

3. Code example for outputting logs

package jpm.logback;    
import org.slf4j.Logger;    
import org.slf4j.LoggerFactory;    
public class TestLogback {        
    public static void main(String[] args) {            
      final Logger LOGGER = LoggerFactory.getLogger(TestLogback.class);
      LOGGER.debug("print debug log.");
      LOGGER.info("print info log.");
      LOGGER.error("print error log.");
   }
}

4. Print log results

36346416b08517b664262a0bcbe1b4a5.png

a42fd85ab6bffab40fccb69e5097c600.jpeg

The above example uses SLF4J as the logging interface and Logback as the log implementation example.

Later, I will introduce you to the Log4j2 usage examples in the project .

Guess you like

Origin blog.csdn.net/z123456789XDW/article/details/132373074