Java Basics - Logging, Getting Started with Logback

log

(1) Logs in the program:

  • The log in the program can be used to record the information during the running of the program and store it permanently.

 (2) Advantages of log technology:

  • The information executed by the system can be selectively recorded to the specified location (console, file, database).
  • You can control whether to record logs at any time in the form of lighting without modifying the source code.
  • Multi-threaded, better performance.

(3) Log architecture:

1. Log specification: Some interfaces provide the standard for log implementation framework design.

  • Commons Logging (JCL)
  • Simple Logging Facade for Java (slf4j) ==> Because someone is not satisfied with the interface of JCL, SLF4J was created.

2. Logging framework: Logging implementation codes that have been prepared by experts or third-party companies can be used directly by newcomers.

  • Log4j
  • CHRISTMAS(java.util.logging)
  • Logback ==> Because I was not satisfied with the performance of Log4j, I started Logback.
  • other implementations

Logback 

(1) Logback log framework: (official website: https://logback.qos.ch/ )

  • Logback is another open source log component designed by the founder of log4j, which has better performance than log4j.
  • Logback is a framework implemented based on slf4j's log specification.

(2) Logback is mainly divided into three technical modules:

  • logback-core: The logback-core module lays the foundation for the other two modules and must be present.

  • logback-classic: It is an improved version of log4j, and it fully implements the slf4j API.
  • The logback-access module integrates with Servlet containers such as Tomcat and Jetty to provide HTTP access logging functionality.

 (The use of Logback requires the use of: slf4j-api, logback-core, logback-classic three modules)

(3) Import the Logback log technology into the project to record the log information of the system. The operation is as follows:

1. Create a new folder lib (dependent library file) under the project, import the related jar package of Logback into the folder, and add it to the project dependent library.

  • Download the three modules required by Logback from the official website, that is, three jar packages:

 

 

 

 

  •  Add to the project dependency library:

 

 2. Copy the core configuration file logback.xml of Logback directly to the src directory (must be under src):

 

Copy the following code into the configuration file in:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- CONSOLE :表示当前的日志信息是可以输出到控制台的 -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <!--输出流对象 默认 System.out 改为 System.err  其中err:控制台输出日志为红色,而out为黑色-->
        <target>System.out</target>
        <encoder>
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level]  %c [%thread] : %msg%n</pattern>
        </encoder>
    </appender>

    <!-- File:表示当前的日志信息是可以输出到文件的 -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
            <charset>utf-8</charset>
        </encoder>
        <!--日志输出路径(logback_message.log是文档名,下方还有一处文件名(不用写.log))-->
        <file>E:\code\javasepromax\Logbacktest\logback_message.log</file>
        <!--指定日志文件拆分和压缩规则(防止文件过大)-->
        <rollingPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!--通过指定压缩文件名称,来确定分割文件方式-->
            <fileNamePattern>E:\code\javasepromax\Logbacktest\logback_message-%d{yyyy-MMdd}.log%i.gz</fileNamePattern>
            <maxFileSize>1MB</maxFileSize> <!--文件拆分大小-->
        </rollingPolicy>
    </appender>

    <!--
    level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF (关掉), 默认debug(可忽略大小写)
    <root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
    -->
    <root level="INFO"> <!--打印规则:只打印不低于当前级别的日志-->
        <appender-ref ref="CONSOLE"/> <!--如果这个地方不配置关联打印的位置,改位置将不会记录日志-->
        <appender-ref ref="FILE" />
    </root>
</configuration>

 Among them, the output address of the log file needs to be modified to your own

 3. Get the log object in the code:

public static final Logger LOGGER = LoggerFactory.getLogger("class object");

For example: 

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 目标:快速搭建Logback日志架构 记录程序的执行情况到控制台 到文件
 */
public class Demo01 {
    //创建Logback的日志对象,代表日志技术
    public static final Logger LOGGER = LoggerFactory.getLogger("Test.class");

    public static void main(String[] args) {
        try {
            LOGGER.debug("main方法开始执行。");
            LOGGER.info("开始记录第二行日志,准备开始除法运算");
            int a = 10;
            int b = 0;
            LOGGER.trace("a=" + a);
            LOGGER.trace("b=" + b);
            System.out.println(a/b);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("功能出现异常" + e);
        }
    }
}

 result:

Guess you like

Origin blog.csdn.net/weixin_61275790/article/details/130095942