当前位置:网站首页>Log framework [detailed learning]
Log framework [detailed learning]
2022-07-23 18:42:00 【Xiao Kai, who loves fishing】

One 、 Log overview
1、 The level of logging
For different scenes , Logs are divided into five levels , In order of importance
- DEBUG Level logs record information that is helpful to the debugger .
- INFO The level of log It is used to record the program operation site , Although no error occurred here , But it has guiding significance for troubleshooting other errors .
- WARN Level log can also be used to record the program running site , But it is more inclined to indicate that there is a possibility of potential errors here .
- ERROR The level log indicates that an error has occurred in the current program operation , Need to be noticed . But the current error , It does not affect the continuous operation of the system .
- FATAL The level log indicates that there is a serious error event in the current program operation , And will lead to Interrupt with program .
2、 journal frame
Terms about log framework such as :log4j、logback、slf4j、jdk-logging、commons-logging, What are these referring to , What's the relationship between them ? Here's the picture , The logging framework is divided into three parts : Log facade 、 Log adapter 、 Log Library . Use facade design pattern to decouple interface and implementation , Make it easier to use logs .
Log Library
Realize the related functions of log , There are three mainstream log repositories , Namely log4j、log-jdk、logback;
among log4j and logback From the same author ,logback yes log4j Upgraded version , And it realizes slf4j Log facade interface ;
log-jdk It is from JDK1.4 Later provided .
Because the implementation of these two kinds of logs is different , Therefore, users need to pay attention to specific details when using , This leads to the following log facade .Log facade
The log facade only provides a set of interface specifications , Not responsible for the implementation of logging function , The purpose is to make users don't need to care about which log base is responsible for log printing and use details .
At present, the most widely used log facade is slf4j and common-logging.
Facade design pattern is one of object-oriented design patterns , The logging framework adopts this mode ( Be similar to JDBC).Log adapter
Facade adapter :
Log facade (slf4j) Norms came later , Therefore, the log library does not implement a facade interface , So think about slf4j+log4j The mode of requires a log facade adapter (slf4j-log4j12) To solve the problem of interface incompatibility .
Logstore adapter :
Some old projects have directly used the log Library API, But there are too many places to print logs , It's hard to change , So we need an adapter to complete the process of API Go to the front log (slf4j)API The routing , In this way, you can use the log facade without changing the original code (slf4j) To uniformly manage logs , And it does not affect the switching of the later day library .
Two 、 The logstore uses
Log facade and log frame selection : If it is a new project, it is recommended to use logback+slf4j Pattern , because logback Self actualization slf4j Interface of facade , There is no need to introduce a facade adapter ; meanwhile logback yes log4j Upgraded version . Have more than log4j More benefits . If you use log4j You need to introduce the corresponding facade adapter . This article will introduce these two ways of use .
1、slf4j + logback Pattern
- Introduce dependencies
<dependency>
<groupid>org.slf4j</groupid>
<artifactid>slf4j-api</artifactid>
<version>${slf4j-ap vers on}</vers on>
</dependency>
<dependency>
<groupid>ch.qos.logback</groupid>
<artifactd>logback-classic</artifactid>
<version>{logback-class c.version}</version>
</dependency>
<dependency>
<groupid>ch.qos.logback</groupid>
<artifactid>logback-core</artifactd>
<version>${logback-core.version)</version>
</dependency>
- Log profile :logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- Logback Configuration. -->
<configuration debug="false" packagingData="${log.packagingData}">
<!-- 1、 introduce .properties, You can use one of the configuration items -->
<property resource="application.properties"/>
<!-- 2、 Console output -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!-- 1 Format output : See another blog post for log format -->
<pattern>
[%X{requestId}] %d{yy/MM/dd HH:mm:ss.SSS} %green(%-5level) [%-15.15thread] %X{EAGLEEYE_TRACE_ID}
%X{EAGLEEYE_RPC_ID} %cyan(%-35.35logger{34}) - %msg%n
</pattern>
<charset>utf-8</charset>
</encoder>
</appender>
<!-- 3、 Log output level : The log level comes from the configuration file -->
<root level="${log.level}">
<appender-ref ref="STDOUT" />
</root>
</configuration>
- Load log profile
If the file is named logback-spring.xml perhaps logback.xml Then put the file in resource The framework under the root directory can automatically recognize . Other names need to be displayed in application.properties Specify the file location in the file :logging.config=classpath:log/logback-spring.xml
Profile naming :
The official recommended name is logback-spring.xml, Because in order to -spring The configuration file at the end can use springProfile label , This tag can use environment variables . Of course, you can customize other names . Other names need to configure the file path in the configuration file as above .
- Print logs using the log frame
Get the factory of the log object LoggerFactory It should be the log facade slf4j Medium org.slf4j It's a bag
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger= LoggerFactory.getLogger(Abc.class);
2、slf4j + slf4j-log4j12 + log4j Pattern ( Later supplement )
3、 ... and 、 Log framework usage specification
1、 Log file name
- Log file naming basis
You should know what application the log file belongs to , What type , What is the purpose , It is conducive to classification and search . - Name recommendation
apply name _ Log type _ Log file name .log(appName_logType_logName.log)
Log types are recommended :stats state ,monitor monitor ,visit Visit, etc
Log file name : Description of log content
2、 Log retention period
The log retention time is too long , It will cause great pressure on disk storage , The storage is too short, which is not conducive to discovery. The frequency is week ( Personally, it means iteration cycle ) Abnormal occurrence , Therefore, it is recommended to keep logs at least 15 God , Of course, according to the purpose and importance of the log, the storage life can be appropriately extended .
3、 Log contents
- The standard of log output
Logs are used to quickly locate problems , But more is not better , Too much will reduce the system performance , So we must think : Is this log read by anyone ; What can I do when I see this log ; Can we improve the efficiency of troubleshooting . - Log output mode
Considering the system operation efficiency and log printing requirements , in the light of DEBUG and INFO Level of logging , You should use placeholders to print , Otherwise, it is printed in the way of conditional judgment , String splicing is used instead of placeholders , Even if the log is not printed, the system will perform string splicing , Thus, system resources are wasted .
// Use placeholders {} form : This is the recommended way
logger.debug ("Processing trade with iJ: {} and nbol{}",id, synbol)
// Make clear the condition to judge the form : It is not recommended to use , Because if you don't add if Judgment statement ,logger Logs will be string spliced at any log level , Even if you don't enter the log .
if (logger.isDebugEnabled()) {
logger.debug (” Processing trade with id:” + id + ” and symbol : " + symbol) ;
}
- Log output level
Production environment prohibit output DEBUG journal , Selective output INFO journal , And pay attention to the log output , By setting a reasonable log file life cycle , Even if you clean up the log , Avoid running out of disk space . - Avoid duplicate printing
Avoid duplicate printing , Be sure to set additivity=false:
<logger name="com.taobao.ecrm.member.config" additivity="false">
- Distinguish between error logs
ERROR Level of logging , Only system logic errors should be recorded 、 Logs of exceptions or violations of business rules , Once these errors occur, manual access is required ; Otherwise, it should be recorded WARN journal , If the user enters wrong parameters, it will cause an exception , This time should be recorded WARN The level of log , The purpose is to restore the on-site situation during user consultation . - Ensure the integrity of records ( Context information of the site , Stack information for exceptions )
Log if output object instance , Make sure the instance rewrites toString() Method , Otherwise, only the instance will be printed hashCode value , It makes no sense .
When recording exceptions, be sure to output the stack information of the exception
logger.error("parameters:{}",parameter,e)

边栏推荐
猜你喜欢

Redis【2022最新面试题】

程序员最想干的三件事 |漫画

Great God "magic change" airpods, equipped with usb-c interface, 3D printing shell makes maintenance easier

到底适不适合学习3D建模?这5点少1个都不行

从业务开发中学习和理解架构设计

Spark 安装与启动

Problems and methods of creating multiple projects under one solution in VS2010

【重磅】聚焦券商终端业务,博睿数据发布新一代券商终端核心业务体验可观测平台

Rhcsa Notes 6

Prevent and control the summer market blowout after adjustment, and evaluate the summer activities of Tujia, muniao and meituan
随机推荐
【2022】【论文笔记】太赫兹量子阱——
【2018】【论文笔记】石墨烯场效应管及【2】——石墨烯的制备、转移
Redis【超强超细 入门教程】
从业务开发中学习和理解架构设计
Modeling at the beginning of learning is very confused, how to learn next generation role modeling?
My creation anniversary
UAV circulating an unknown target under a GPS deniedenvironment with range only measurements translation
Jetpack Compose之Navigation组件使用
[toggle 30 days of ML] Diabetes genetic risk detection challenge (2)
如何理解:普通代码块、构造块、静态块?有什么关系?
DB9 serial port and RJ45 serial port
Behind the recovery of the B-END Market: who stands in front of the stage?
1259. 不相交的握手 动态规划
Spark installation and startup
Ubuntu 22.04 installing mysql8
How to realize the digital transformation of the banking industry
大神“魔改”AirPods,配备USB-C接口,3D打印外壳让维修更容易
【攻防世界WEB】难度四星12分进阶题:Cat
我的创作纪念日
Does anyone get a job by self-study modeling? Don't let these thoughts hurt you