Home > Java > javaTutorial > body text

How to use log4j2 logging in Springboot

WBOY
Release: 2023-05-22 08:58:11
forward
1050 people have browsed it

Commonly used logging framework

  • java.util.logging: It is the Java native logging framework introduced by JDK in version 1.4

  • Log4j: An open source project of Apache. It can control the destination of log information transmission to the console, files, GUI components, etc. It can control the output format of each log. These can be flexibly controlled through a configuration file. Configurable without modifying the application code. Although maintenance has been stopped, most companies currently use log4j.

  • LogBack: It is an improved version of Log4j

  • Log4j2: Log4j2 is not just an upgraded version of Log4j, it is from beginning to end All have been rewritten

Log facade slf4j

The above introduces the implementation of some log frameworks, here we need to use logs Facade to solve the coupling between the system and the log implementation framework. SLF4J, Simple Logging Facade for Java, is not a real logging implementation, but an abstraction layer that allows you to use any logging implementation in the background.

How to use log4j2 logging in Springboot

The same as the several log frameworks introduced earlier, each log framework has its own separate API. To use the corresponding framework, you must use its corresponding API. This This greatly increases the coupling of the application code to the logging framework.

After using slf4j, for applications, no matter how the underlying logging framework changes, the application can go online directly without modifying any line of code.

Why choose log4j2

Compared with other log systems, log4j2 loses less data; disruptor technology, in a multi-threaded environment, has higher performance than logback Wait more than 10 times; take advantage of the concurrency features of jdk1.5 to reduce the occurrence of deadlocks;

The reason for the superior performance of log4j2 is that log4j2 uses LMAX, a lock-free inter-thread communication library instead of logback And the queue before log4j. Concurrency performance is greatly improved.

Integration steps

Introducing the Jar package

springboot uses the logback log framework by default, so logback needs to be excluded. Otherwise, there will be an error report of jar dependency conflict.

<dependency> 
 <groupid>org.springframework.boot</groupid> 
 <artifactid>spring-boot-starter-web</artifactid> 
 <exclusions><!-- 去掉springboot默认配置 --> 
  <exclusion> 
   <groupid>org.springframework.boot</groupid> 
   <artifactid>spring-boot-starter-logging</artifactid> 
  </exclusion> 
 </exclusions> 
</dependency> 

<dependency> <!-- 引入log4j2依赖 --> 
 <groupid>org.springframework.boot</groupid> 
 <artifactid>spring-boot-starter-log4j2</artifactid> 
</dependency>
Copy after login

Configuration file

If you customize the file name, you need to configure it in application.yml

logging:
 config: xxxx.xml
 level:
 cn.jay.repository: trace
Copy after login

The default name is log4j2-spring.xml, This saves the need to configure the

configuration file template in application.yml

log4j uses a .properties file as the main configuration file, and now log4j2 This method has been abandoned, and the .xml, .json or .jsn method is used. This may be an inevitability of technological development, because the readability of the properties file is really poor.

<?xml  version="1.0" encoding="UTF-8"?>
<!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出-->
<!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
<configuration>
 <!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->

 <!--变量配置-->
 <properties>
 <!-- 格式化输出:%date表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %msg:日志消息,%n是换行符-->
 <!-- %logger{36} 表示 Logger 名字最长36个字符 -->
 <property></property>
 <!-- 定义日志存储的路径,不要配置相对路径 -->
 <property></property>
 <property></property>
 </properties>

 <appenders>

 <console>
  <!--输出日志的格式-->
  <patternlayout></patternlayout>
  <!--控制台只输出level及其以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
  <thresholdfilter></thresholdfilter>
 </console>

 <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,适合临时测试用-->
 <file>
  <patternlayout></patternlayout>
 </file>

 <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
 <rollingfile>
  <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
  <thresholdfilter></thresholdfilter>
  <patternlayout></patternlayout>
  <policies>
  <!--interval属性用来指定多久滚动一次,默认是1 hour-->
  <timebasedtriggeringpolicy></timebasedtriggeringpolicy>
  <sizebasedtriggeringpolicy></sizebasedtriggeringpolicy>
  </policies>
  <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
  <defaultrolloverstrategy></defaultrolloverstrategy>
 </rollingfile>

 <!-- 这个会打印出所有的warn及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
 <rollingfile>
  <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
  <thresholdfilter></thresholdfilter>
  <patternlayout></patternlayout>
  <policies>
  <!--interval属性用来指定多久滚动一次,默认是1 hour-->
  <timebasedtriggeringpolicy></timebasedtriggeringpolicy>
  <sizebasedtriggeringpolicy></sizebasedtriggeringpolicy>
  </policies>
  <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
  <defaultrolloverstrategy></defaultrolloverstrategy>
 </rollingfile>

 <!-- 这个会打印出所有的error及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
 <rollingfile>
  <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
  <thresholdfilter></thresholdfilter>
  <patternlayout></patternlayout>
  <policies>
  <!--interval属性用来指定多久滚动一次,默认是1 hour-->
  <timebasedtriggeringpolicy></timebasedtriggeringpolicy>
  <sizebasedtriggeringpolicy></sizebasedtriggeringpolicy>
  </policies>
  <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
  <defaultrolloverstrategy></defaultrolloverstrategy>
 </rollingfile>

 </appenders>

 <!--Logger节点用来单独指定日志的形式,比如要为指定包下的class指定不同的日志级别等。-->
 <!--然后定义loggers,只有定义了logger并引入的appender,appender才会生效-->
 <loggers>

 <!--过滤掉spring和mybatis的一些无用的DEBUG信息-->
 <logger>
  <appenderref></appenderref>
 </logger>
 <!--监控系统信息-->
 <!--若是additivity设为false,则 子Logger 只会在自己的appender里输出,而不会在 父Logger 的appender里输出。-->
 <logger>
  <appenderref></appenderref>
 </logger>

 <root>
  <appender-ref></appender-ref>
  <appender-ref></appender-ref>
  <appender-ref></appender-ref>
  <appender-ref></appender-ref>
  <appender-ref></appender-ref>
 </root>
 </loggers>

</configuration>
Copy after login

Introduction to configuration parameters

Here is a brief introduction to commonly used configuration parameters

Log level

  • Mechanism: If the level of a log message is greater than or equal to the level of the configuration file, it will be recorded.

  • trace: Tracing is to advance the program, you can write a trace output

  • debug: debugging, generally as the lowest level, trace is basically not used .

  • info: Output important information, used more

  • warn: Warning, some information is not error information, but it should also be given to programmers Some tips.

  • error: error message. Used a lot.

  • fatal: Fatal error.

Output source

  • CONSOLE (output to console)

  • FILE (output to file )

Format

  • SimpleLayout: Display in simple form

  • HTMLLayout: In HTML table Display

  • PatternLayout: Custom form display

PatternLayout Custom log layout:

%d{yyyy-MM-dd HH:mm:ss, SSS} : 日志生产时间,输出到毫秒的时间
%-5level : 输出日志级别,-5表示左对齐并且固定输出5个字符,如果不足在右边补0
%c : logger的名称(%logger)
%t : 输出当前线程名称
%p : 日志输出格式
%m : 日志内容,即 logger.info("message")
%n : 换行符
%C : Java类名(%F)
%L : 行号
%M : 方法名
%l : 输出语句所在的行数, 包括类名、方法名、文件名、行数
hostName : 本地机器名
hostAddress : 本地ip地址
Copy after login

Log4j2 configuration details

Root node Configuration

has two attributes:

  • status

  • monitorinterval

has two child nodes:

  • Appenders

  • Loggers (indicates that multiple Appenders and Logger).

status is used to specify the level of log4j’s own print log.

monitorinterval is used to specify the monitoring interval for log4j’s automatic reconfiguration, the unit is s, The minimum is 5s.

Appenders node

There are three common sub-nodes: Console, RollingFile, File

The Console node is used to define the Appender output to the console.

  • name: Specify the name of the Appender.

  • Usually only set the default to SYSTEM_OUT, not SYSTEM_ERR

  • PatternLayout: Output format, if not set, the default is: %m%n.

File node is used to define the Appender that outputs the file to the specified location .

  • name: Specify the name of the Appender.

  • fileName:指定输出日志的目的文件带全路径的文件名.

  • PatternLayout:输出格式,不设置默认为:%m%n.

 RollingFile节点用来定义超过指定条件自动删除旧的创建新的Appender.

  • name:指定Appender的名字.

  • fileName:指定输出日志的目的文件带全路径的文件名.

  • PatternLayout:输出格式,不设置默认为:%m%n.

  • filePattern : 指定当发生Rolling时,文件的转移和重命名规则.

  • Policies:指定滚动日志的策略,就是什么时候进行新建日志文件输出日志.

  • TimeBasedTriggeringPolicy:Policies子节点,基于时间的滚动策略,interval属性用来指定多久滚动一次,默认是1 hour。modulate=true用来调整时间:比如现在是早上3am,interval是4,那么第一次滚动是在4am,接着是8am,12am...而不是7am.

  • SizeBasedTriggeringPolicy:Policies子节点,基于指定文件大小的滚动策略,size属性用来定义每个日志文件的大小.

  • DefaultRolloverStrategy:用来指定同一个文件夹下最多有几个日志文件时开始删除最旧的,创建新的(通过max属性)。

Loggers节点,常见的有两种:Root和Logger.

  • Root节点用来指定项目的根日志,如果没有单独指定Logger,那么就会默认使用该Root日志输出

  • level:日志输出级别,共有8个级别,按照从低到高为:All

  • Logger节点用来单独指定日志的形式,比如要为指定包下的class指定不同的日志级别等。

  • level:日志输出级别,共有8个级别,按照从低到高为:All

  • name:用来指定该Logger所适用的类或者类所在的包全路径,继承自Root节点.

  • AppenderRef:Logger的子节点,用来指定该日志输出到哪个Appender,如果没有指定,就会默认继承自Root.如果指定了,那么会在指定的这个Appender和Root的Appender中都会输出,此时我们可以设置Logger的additivity="false"只在自定义的Appender中进行输出。

简单使用

public class LogExampleOther {
 private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleOther.class);
 
 public static void main(String... args) {
 log.error("Something else is wrong here");
 }
}
Copy after login

使用lombok工具简化创建Logger类

lombok就是一个注解工具jar包,能帮助我们省略一繁杂的代码。具体介绍可以看我的这篇教程。

使用lombok后下面的代码等效于上述的代码,这样会更方便的使用日志。

@Slf4j
public class LogExampleOther {
 
 public static void main(String... args) {
 log.error("Something else is wrong here");
 }
}
Copy after login

The above is the detailed content of How to use log4j2 logging in Springboot. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!