


Spring Boot logging framework practice - hansonwang99's technical sharing
This article mainly shares with you the practice of Spring Boot logging framework. The code part is also very detailed. Friends in need can refer to it.
Overview
In Java applications, logs are generally divided into the following 5 levels:
ERROR Error message
WARN Warning message
INFO General information
DEBUG Debug information
TRACE Trace information
Spring Boot uses Apache’s Commons Logging as the internal logging framework, which is just a log interface , in actual applications, it is necessary to specify the corresponding log implementation for this interface.
The default log implementation of SpringBt is Java Util Logging, which is the log package that comes with the JDK. In addition, SpringBt of course also supports popular log implementations such as Log4J and Logback.
Unify the above log implementation collectively as log framework
Let’s practice it!
Use the Spring Boot Logging plug-in
First add the configuration to the application.properties file:
logging.level.root=INFO
The controller part code is as follows:
package com.hansonwang99.controller; import com.hansonwang99.K8sresctrlApplication; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/testlogging") public class LoggingTestController { private static Logger logger = LoggerFactory.getLogger(K8sresctrlApplication.class); @GetMapping("/hello") public String hello() { logger.info("test logging..."); return "hello"; } }
Running result
Since the log level is set to INFO, log information containing INFO and above levels will be printed
It can be seen here that many and most INFO logs come from the SpringBt framework itself, if we want to block them, we can set the log level to ERROR first, so that the INFO information of the framework itself will not be printed. Then set specific packages in the application to DEBUG level logs, so that you can only see DEBUG and above level logs in the packages you care about.
Control the log level of a specific package
Change the configuration in application.yml
logging: level: root: error com.hansonwang99.controller: debug
Obviously, change the root log level Set it to ERROR, and then set the log level of the com.hansonwang99.controller
package to DEBUG, which means: first disable all and then allow individual setting methods
Controller code
package com.hansonwang99.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/testlogging") public class LoggingTestController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @GetMapping("/hello") public String hello() { logger.info("test logging..."); return "hello"; } }
Running result
- Output the log to a certain file
logging: level: root: error com.hansonwang99.controller: debug file: ${user.home}/logs/hello.log
- Run results
##Using Spring Boot Logging, we found that although the log has been output to the file, a copy will still be printed in the console. We found that using
cannot solve this problem.
- Add dependencies in pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency>
Copy after login
- Add the
- log4j2.xml
file in the resources directory with the following content:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <appenders> <File name="file" fileName="${sys:user.home}/logs/hello2.log"> <PatternLayout pattern="%d{HH:mm:ss,SSS} %p %c (%L) - %m%n"/> </File> </appenders> <loggers> <root level="ERROR"> <appender-ref ref="file"/> </root> <logger name="com.hansonwang99.controller" level="DEBUG" /> </loggers> </configuration>
Copy after login
- Other codes remain unchanged
- Run the program and find that there is no log output on the console, but there is content in the hello2.log file, which is in line with our expectations:
#And the log format is the same as pattern="%d{HH:mm:ss,SSS} %p %c (%L) - %m%n"
Log4J Further practice
pom.xml configuration:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency>
Copy after login
<?xml version="1.0" encoding="UTF-8"?> <configuration status="warn"> <properties> <Property name="app_name">springboot-web</Property> <Property name="log_path">logs/${app_name}</Property> </properties> <appenders> <console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="[%d][%t][%p][%l] %m%n" /> </console> <RollingFile name="RollingFileInfo" fileName="${log_path}/info.log" filePattern="${log_path}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log.gz"> <Filters> <ThresholdFilter level="INFO" /> <ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL" /> </Filters> <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" /> <Policies> <!-- 归档每天的文件 --> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> <!-- 限制单个文件大小 --> <SizeBasedTriggeringPolicy size="2 MB" /> </Policies> <!-- 限制每天文件个数 --> <DefaultRolloverStrategy compressionLevel="0" max="10"/> </RollingFile> <RollingFile name="RollingFileWarn" fileName="${log_path}/warn.log" filePattern="${log_path}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log.gz"> <Filters> <ThresholdFilter level="WARN" /> <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL" /> </Filters> <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" /> <Policies> <!-- 归档每天的文件 --> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> <!-- 限制单个文件大小 --> <SizeBasedTriggeringPolicy size="2 MB" /> </Policies> <!-- 限制每天文件个数 --> <DefaultRolloverStrategy compressionLevel="0" max="10"/> </RollingFile> <RollingFile name="RollingFileError" fileName="${log_path}/error.log" filePattern="${log_path}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz"> <ThresholdFilter level="ERROR" /> <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" /> <Policies> <!-- 归档每天的文件 --> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> <!-- 限制单个文件大小 --> <SizeBasedTriggeringPolicy size="2 MB" /> </Policies> <!-- 限制每天文件个数 --> <DefaultRolloverStrategy compressionLevel="0" max="10"/> </RollingFile> </appenders> <loggers> <root level="info"> <appender-ref ref="Console" /> <appender-ref ref="RollingFileInfo" /> <appender-ref ref="RollingFileWarn" /> <appender-ref ref="RollingFileError" /> </root> </loggers> </configuration>
Copy after login
- Running results
package com.hansonwang99.controller; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/testlogging") public class LoggingTestController { private final Logger logger = LogManager.getLogger(this.getClass()); @GetMapping("/hello") public String hello() { for(int i=0;i<10_0000;i++){ logger.info("info execute index method"); logger.warn("warn execute index method"); logger.error("error execute index method"); } return "My First SpringBoot Application"; } }
Copy after loginThe logs will be stored in different files according to different levels. When the log file size exceeds 2M, it will be divided into multiple files for compressed storage. Log files in the production environment It is recommended to adjust the size to 20-50MB.
Postscript
For more original articles by the author, please see the SF column
More practical articles on SpringBt by the author are here:
-
The practice of ElasticSearch search engine in SpringBoot
Initial exploration of Kotlin+SpringBoot joint programming
Related recommendations:
The 8 most commonly used Java log frameworks by java programmers
The above is the detailed content of Spring Boot logging framework practice - hansonwang99's technical sharing. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics
![Windows ISO file too large BootCamp error [Fixed]](https://img.php.cn/upload/article/000/887/227/170831702395455.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
If you get the error message "The Windows ISO file is too large" when using BootCampAssistant on a Mac computer, this may be because the ISO file size exceeds the limit supported by BootCampAssistant. The solution to this problem is to use other tools to compress the ISO file size to ensure that it can be processed in BootCamp Assistant. BootCampAssistant is a convenient tool provided by Apple for installing and running Windows operating system on Mac computers. It helps users set up a dual-boot system, allowing them to easily choose to use MacOS or Wind at startup

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

As an email manager application, Microsoft Outlook allows us to schedule events and appointments. It enables us to stay organized by providing tools to create, manage and track these activities (also called events) in the Outlook application. However, sometimes unwanted events are added to the calendar in Outlook, which creates confusion for users and spams the calendar. In this article, we will explore various scenarios and steps that can help us prevent Outlook from automatically adding events to my calendar. Outlook Events – A brief overview Outlook events serve multiple purposes and have many useful features as follows: Calendar Integration: In Outlook

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

Principle analysis and practical exploration of the Struts framework. As a commonly used MVC framework in JavaWeb development, the Struts framework has good design patterns and scalability and is widely used in enterprise-level application development. This article will analyze the principles of the Struts framework and explore it with actual code examples to help readers better understand and apply the framework. 1. Analysis of the principles of the Struts framework 1. MVC architecture The Struts framework is based on MVC (Model-View-Con

PHP Coding Practices: Refusal to Use Alternatives to Goto Statements In recent years, with the continuous updating and iteration of programming languages, programmers have begun to pay more attention to coding specifications and best practices. In PHP programming, the goto statement has existed as a control flow statement for a long time, but in practical applications it often leads to a decrease in the readability and maintainability of the code. This article will share some alternatives to help developers refuse to use goto statements and improve code quality. 1. Why refuse to use goto statement? First, let's think about why
