Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use SpringBoot to integrate slf4j log configuration

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use SpringBoot to integrate slf4j log configuration, the article is very detailed, has a certain reference value, interested friends must read it!

1. Overview of slf4j

Slf4j, namely (Simple Logging Facade for Java, simple facade log). It is a specification, standard and interface for all logging frameworks, and it is not a specific implementation of a framework, it only serves a variety of logging systems.

Slf4j provides a unified interface for logging, abstracting the specific implementation of different log systems, as long as it can be recorded according to the method it provides, and the final log format, recording level, output mode and so on are realized by binding the specific log system. Slf4j logging is used in the project, and log4j is bound (the corresponding jar package dependency is configured in pom.xml), then the log will be output in the style of log4j; later, you need to output the log in the style of logback, just replace the jar package log4j with logback, and there is no need to modify the code of the log file at all.

First, take a look at log printing, as shown below, to introduce Logger logging in the startup class:

@ SpringBootApplicationpublic class SpringbootSlf4jApplication {private static final Logger logger = LoggerFactory.getLogger (SpringbootSlf4jApplication.class); public static void main (String [] args) {logger.info ("= project started ="); SpringApplication app = new SpringApplication (SpringbootSlf4jApplication.class); app.run (args); logger.info ("= started successfully =");}}

Log information:

2020-03-21 11 2818. 017 [main] INFO com.hl.magic.slf4j.SpringbootSlf4jApplication-= Project started =

2020-03-21 11 Starting SpringbootSlf4jApplication on DESKTOP-V8RSTKO with PID 28 18. 447 [main] INFO com.hl.magic.slf4j.SpringbootSlf4jApplication-Starting SpringbootSlf4jApplication on DESKTOP-V8RSTKO with PID 17476

2020-03-21 11 Running with Spring Boot v2.1.8.RELEASE 2818. 447 [main] DEBUG com.hl.magic.slf4j.SpringbootSlf4jApplication-Running with Spring Boot v2.1.8.RELEASE, Spring v5.1.9.RELEASE

2020-03-21 11 falling back to default profiles 2818. 447 [main] INFO com.hl.magic.slf4j.SpringbootSlf4jApplication-No active profile set, default

2020-03-21 11 Tomcat initialized with port 2819.077 [main] INFO o.s.boot.web.embedded.tomcat.TomcatWebServer-Tomcat initialized with port (s): 8080 (http)

2020-03-21 11 Initializing ProtocolHandler 2819.087 [main] INFO org.apache.coyote.http11.Http11NioProtocol-Initializing ProtocolHandler ["http-nio-8080"]

2020-03-21 11 Starting service 2819.097 [main] INFO org.apache.catalina.core.StandardService-Starting service [Tomcat]

2020-03-21 11 Starting Servlet engine 2819.097 [main] INFO org.apache.catalina.core.StandardEngine-Starting Servlet engine: [Apache Tomcat/9.0.24]

2020-03-21 11 Freud 2819.157 [main] INFO o.a.c.core.ContainerBase.[ tomcat] .[ localhost]. [/]-Initializing Spring embedded WebApplicationContext

2020-03-21 11 ms 2819.157 [main] INFO org.springframework.web.context.ContextLoader-Root WebApplicationContext: initialization completed in 680

2020-03-21 11 Initializing ExecutorService 2819.287 [main] INFO o.s.scheduling.concurrent.ThreadPoolTaskExecutor-Initializing ExecutorService 'applicationTaskExecutor'

2020-03-21 11 Starting ProtocolHandler 2819.387 [main] INFO org.apache.coyote.http11.Http11NioProtocol-Starting ProtocolHandler ["http-nio-8080"]

2020-03-21 11 Freud 2819. 397 [main] INFO o.a.c.core.ContainerBase.[ Tomcat] .[ localhost]. [/]-Initializing Spring DispatcherServlet 'dispatcherServlet'

2020-03-21 11 Freud 2819.397 [main] INFO org.springframework.web.servlet.DispatcherServlet-Initializing Servlet' dispatcherServlet'

2020-03-21 11 ms 2819.407 [main] INFO org.springframework.web.servlet.DispatcherServlet-Completed initialization in 10 ms

2020-03-21 11 with context path 2819.410 [main] INFO o.s.boot.web.embedded.tomcat.TomcatWebServer-Tomcat started on port (s): 8080 (http) with context path''

2020-03-21 11 seconds 2819.410 [main] INFO com.hl.magic.slf4j.SpringbootSlf4jApplication-Started SpringbootSlf4jApplication in 1.323 seconds (JVM running for 2.024)

2020-03-21 11 2819.410 [main] INFO com.hl.magic.slf4j.SpringbootSlf4jApplication-= started successfully

GetLogger (xxxxxxx.class); this method passes the current class as an input parameter, and the output log displays the corresponding xxx class name. The advantage of this declaration is that it is easy to locate the log, and the accurate writing of class information can provide the efficiency of quickly locating the log.

However, although slf4j is provided internally in SpringBoot, logging needs to be configured according to the needs of the project in order to maximize its effectiveness. OK, let's take a look at the configuration of the SpringBoot project integration slf4j log.

2. Log dependence of pom.xml

The log dependency configuration in pom.xml is as follows:

Log configuration of org.slf4j slf4j-api 1.7.30 org.slf4j slf4j-log4j12 1.7.303 and application.yml

Slf4j has been integrated within the SpringBoot framework, and when in use, it is necessary to specify the configuration of slf4j according to the needs of the project in the field.

Application.yml file is a very important and core configuration file of SpringBoot. Yml files have a strong sense of hierarchy and intuition, but the format requirements are relatively high, English colons must be followed by a space, if the line-breaking configuration child, you must freeze input two spaces before configuration, otherwise the project is estimated to be unable to start, and do not report an error. The log configuration in the application.yml of this test project is as follows:

Logging: config: / HL/IdeaProjects/SpringBoot-Item/springboot-slf4j/src/main/resources/logback.xml level: com.hl.magic: trace

Note:

[1] the configuration of logback.xml here is different from the general log configuration.

Because in a separate SpringBoot project, configure the config tag as: locbak.xml

Here the log configuration is integrated in a child Module of the SpringBoot project, so at the config tag, it is set to the absolute path.

[2] logging.config is used to specify which configuration file to read when the project starts. Here, the log configuration file is specified, that is, the logback.xml file under the root path of the sub-module project, which is the main configuration information of the log.

[3] level is used to configure the logging of the application under the path of the specified package, and its log level.

Logging.level is used to specify the output level of the application log in a specific package. The above configuration indicates that all log output levels under the com.hl.magic package are trace, which will print out the sql that operates the database, and set it to trace to locate the problem during development. In the production environment, you can set this log level to error level again.

The five commonly used levels of logging, from low to high severity, are: debug (debugging)

< info(消息) < warn(警告) < error(错误) < fatal(严重错误)。通常可以根据实际所需要的颗粒度的大小选择其中的几个,当前常用debug,info,warn,error4个级别。 4、logback.xml配置文件定义 在引入日志配置后,需要制定日志的配置文件内容,这样系统运行后,根据定制化需求才能输出我们所需的指定日志记录信息。 本文测试用例的日志配置内容logback.xml文件,详细内容如下: %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n ${LOG_HOME}/SpringBoot-Slf4j_%d{yyyy-MM-dd}.log 30 %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n 10MB 有上边可以看出,我们可以轻松的在logback.xml中定义日志输出的格式、路径、控制台输出格式、文件大小、保存时长等内容。接下来,就这些内容进行分析。 5、logback.xml配置文件解析 5.1 定义日志的存储路径 logback.xml文件中日志存储路径定义: 分析: 首先,定义日志的名称:LOG_HOME; 其次,设置输出value定义为日志的存储路径,日志都会存储在该路径下。 注意:这里勿在logback文件中使用相对路径,不管是 windows 系统还是 Linux 系统,日志存储的路径必须要是绝对路径。 5.2 定义日志的输出格式 分析: 首先,定义日志格式的名称:LOG_PATTERN 其次,设置日志的具体格式value。 "%d" 表示日期(也可以使用"%date"); "%-5level" 表示级别从左显示5个字符宽度; "%thread" 表示线程名; "%-30.30logger{30}" 表示如果logger的名称小于30,就"-"指定左对齐;如果其名称长于30字符,就从左边较远输出的字符截掉,保持logger的名字长度最终限制为30个字符; "%msg" 表示日志消息,`%n` 是换行符。 5.3 定义控制台输出 ${LOG_PATTERN} 分析: 使用 标签设置控制台输出(`class="ch.qos.logback.core.ConsoleAppender"`)的配置,定义为 "CONSOLE"。使用引入变量的方式: ${LOG_PATTERN}引进来即可。引入上面定义好的输出格式(LOG_PATTERN)来输出 这里,也可以直接配置格式化输出结果的方式,不过体力工作。 5.4 定义日志相关参数 在标签内定义一个名为 "FILE" 的文件参数配置。主要是配置日志文件的输出文件名、日志文件保留时间、日志文件保存的路径和日志的输出格式、及单个日志文件存储的大小。 ${LOG_HOME} 30 ${LOG_PATTERN} 10MB 分析: 这里,根据前面配置的日志变量,引入到配置日志文件的输出文件名、日志文件保留时间、日志文件保存的路径和日志的输出格式、及单个日志文件存储的大小的各个标签项即可。 5.5 定义日志的输出级别 在完成前边的准备工作后,最后来定义一下日志的输出级别: 分析: 在标签中来项目默认的日志输出级别,这里定义级别为ERROR(用在生产环境中),然后针对ERROR级别的日志,使用引用上面定义好的控制台日志输出和日志文件的参数。这样 logback.xml 文件中的配置就设置完了。 注意: 标签并不是只能添加一个,我们还可以指定项目特定包路径的日志输出级别。 本文测试类配置日志输出级别为:DEBUG,使用最低日志输出级别,确保后边测试时能够打印出所有测试项。如果需要改变日志级别就在上面配置内容修改即可。 6、测试日志输出 在程序中,一般使用 Logger(注意引jar包为slf4j) 对象来打印出一些日志信息,可以指定打印出的日志级别,也支持占位符。 定义一个测试类:LoggerItemController.java /** * 日志输出测试的controller */@RestController@RequestMapping("/loggerItem")public class LoggerItemController { private static final Logger logger = LoggerFactory.getLogger(LoggerItemController.class); @GetMapping("/logInfo") public ResponseMessage logTest(){ logger.debug("=====>

Test log debug level print test log info level print test log warn level print AndOne, CSDN blog: {}; AndOne, GitHub address: {}; ", csdn, git); return new ResponseMessage (ResponseStatus.SUCCESS.getStatus (), ResponseStatus.SUCCESS.getMessage ());}}

Start the project first, and visit the browser at 127.0.0.1:8080/loggerItem/logInfo

View console print information:

= > Test log debug level print test log info level print test log error level print warn level print AndOne, CSDN blog: https://blog.csdn.net/qq_27706119 / AndOne, GitHub address: https://github.com/JohnnyHL

In the output level of the log, DEBUG is the lowest level, so that all information can be printed out. If you increase the log output level, for example, select INFO. Then the record of DEBUG will not be printed, and you can test it yourself. At the same time, take a look at the previously configured log storage path: the "/ HL/IdeaProjects/SpringBoot-Item/springboot-slf4j/log" directory, where the project startup and all log records generated later are recorded. During the daily development process, after the project is deployed, you can locate the problem by looking at the log file.

The above is all the content of the article "how to use SpringBoot to integrate slf4j log configuration". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report