Custom configuration log log

Table of contents

The log that comes with springboot

Configure new log files

1. Create a new log configuration file

2. Write the content of the configuration file

3. Write a custom log log - file printing

Modify the official log format

1. @Slf4j needs to be used here

2. Need to add a placeholder in the xml log configuration file - custom parameter %X{key value}

3. Modify the format

Bonus: Custom Banner


Background: When working on a project, I want to customize the logs that I want to output in some projects

The log that comes with springboot

When there is no configuration in the project, springboot will output its own log format by default.

Configure new log files

1. Create a new log configuration file

If you want to customize the log file, you need to customize a log file - naming is very important

2. Write the content of the configuration file

Write a log log in the default format

The content of the configuration file --- when the file is created, if nothing is written in it, then when we start the project, the console will not play anything (except for Banner, Banner can also be set to what you like - later introduce to you)

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!--配置为空-->
</configuration>

Write a default log configuration file - using the default is equivalent to no configuration

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!--    控制台打印——使用springboot默认日志格式-->
<!--  这个文件会默认覆盖springboot的日志  如果里边什么也不写的话 那么启动程序的时候就会什么也不显示   -->
    <!--这个是引入了springboot的默认日志格式-->
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
<!--  引入预设默认样式  引入后打印的就像是最一开始springboot打印的日志了         这个里边的${CONSOLE_LOG_PATTERN} 是ExternalLibraries中springframework.boot:spring-boot:2.6.2中的defaults.xml中CONSOLE_LOG_PATTERN-->
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>${CONSOLE_LOG_CHARSET}</charset>
        </encoder>
    </appender>
<!--    指定日志输出级别  以及启用的APPender 这里使用的我们上边的ConsoleAppender-->
<!--    日志级别:从低到高 TRACE<DEBUG<INFO<WARN<ERROR<FATAL  springboot默认只会打印INFO以上的级别信息-->
    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
    </root>
    <!--    控制台打印——使用springboot默认日志格式-->
</configuration>

Console print - the same output as when there is no configuration

3. Write a custom log log - file printing

We only need to configure a corresponding Appender

Introduce RollingFileAppender for file logging

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <!--    控制台打印——使用springboot默认日志格式-->
    <!--  这个文件会默认覆盖springboot的日志  如果里边什么也不写的话 那么启动程序的时候就会什么也不显示   -->
    <!--这个是引入了springboot的默认日志格式-->
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!--  引入预设默认样式  引入后打印的就像是最一开始springboot打印的日志了   这个里边的${CONSOLE_LOG_PATTERN} 是ExternalLibraries中springframework.boot:spring-boot:2.6.2中的defaults.xml中CONSOLE_LOG_PATTERN-->
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>${CONSOLE_LOG_CHARSET}</charset>
            <!--  引入预设默认样式  引入后打印的就像是最一开始springboot打印的日志了   这个里边的${CONSOLE_LOG_PATTERN} 是ExternalLibraries中springframework.boot:spring-boot:2.6.2中的defaults.xml中CONSOLE_LOG_PATTERN-->
        </encoder>
    </appender>

<!--ch.qos.logback.core.rolling.RollingFileAppender用于文件日志记录,并且支持滚动  有滚动策略-->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
<!--                依然使用默认的日志格式-->
            <pattern>${FILE_LOG_PATTERN}</pattern>
            <charset>${FILE_LOG_CHARSET}</charset>
        </encoder>
<!--            自定义滚动策略,防止日志文件无限变大,也就是日志文件写到什么时候为止,重新创建一个新的日志文件-->
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--                文件保存位置以及文件命名规则,这里用到了%d{yyyy-MM-dd}表示当前日期,%i表示这一天的第N个日志-->
            <FileNamePattern>log/%d{yyyy-MM-dd}-spring-%i.log</FileNamePattern>
<!--                到期自动清理日志文件-->
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
<!--                最大日志保留时间-->
            <maxHistory>7</maxHistory>
<!--                最大单个日志文件大小-->
            <maxFileSize>10MB</maxFileSize>
        </rollingPolicy>
    </appender>
    <!--ch.qos.logback.core.rolling.RollingFileAppender用于文件日志记录,并且支持滚动  有滚动策略-->

    <!--    指定日志输出级别  以及启用的APPender 这里使用的我们上边的ConsoleAppender-->
    <!--    日志级别:从低到高 TRACE<DEBUG<INFO<WARN<ERROR<FATAL  springboot默认只会打印INFO以上的级别信息-->
    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
         <!-- 一定要在这写上  不然不会生效 -->
        <appender-ref ref="FILE"/>
    </root>
    <!--    控制台打印——使用springboot默认日志格式-->
</configuration>

After the configuration is complete, when we start the project, we will find that our Appender automatically generates a package for storing logs and a log file for us.

Modify the official log format

 Official documentation: LOGBack official website

There are still relatively few built-in log fields in logback. If we need to print more content about the business, including some custom data, we need to use the logback MDC mechanism MDC as "Mapped Diagnostic Context" The context data is printed out through logback, at this time we need to use the rog.sl4j.MDC class

Basic fields of the log

For example: now we need to record the log of which user visited our website. As long as this user visits my website, the user’s id will be carried in the log. We hope that each log will carry such a piece of information text, and the official provides The field cannot implement this function, then you need to use the MDC mechanism:

1. @Slf4j needs to be used here

@Slf4j
@Controller
public class MainController{

	@RequestMapping("/login")
	public String login(){
		//这里使用Session代替id  实际使用可以替换成想要记录的字段
		MDC.put("reqId",request.getSession().getId());
		log.info("用户访问了一次登录界面")
  	return "login";

		}
} 

2. Need to add a placeholder in the xml log configuration file - custom parameter %X{key value}

When we add information to MDC, as long as the log output under the current thread (essentially implemented by ThreadLocal), the placeholder will be automatically replaced

<!--  %clr是springboot定义的()中的是要显示的字段和值  {faint}也是springboot定义的  -->

%clr([%X{reqId}]){faint}

3. Modify the format

1. First copy the default log format into our log configuration file

Copy to logback-spring.xml

2. Replace custom fields

Remove CONSOLE_LOG_PATTERN

!!! Note that there is still half a "}" at the end to be removed

Add newly defined fields

 test:

@Controller
@RequestMapping("/demo")
public class DemoController {
    @RequestMapping("/login")
    public String login(HttpServletRequest request){
        //这里用Session代替ID
        MDC.put("reqId",request.getSession().getId());
        return "login";
    }

4. Start the project

We can see that there is an extra parenthesis (behind ---)

Send a request - we can see that the Session of our terminal is recorded

You can also add a description after this class --- use needs to add @Slf4j annotation

log.info("手动添加日志信息")

At this point, the customization and format replacement of our log has been modified. You can print the project log on demand according to actual needs.

Bonus: Custom Banner

When we use the blank logback-spring.xml file to overwrite the springboot default log at the beginning, we can see that the Banner part and the log part are independent. After springboot starts, the Banner part will be printed first, so we can customize the style of the Banner configuration.

step:

1. Create a new Banner.txt file under resources

2. Set the pattern you want to display in the banner - choose it yourself in this link

We can also add some version information to the Banner, such as the version of springboot, etc.

Banner Pattern Daquanhttps ://www.bootschool.net/ascii-art

                                   ___
                                 ./  _)                                               O
                          _.---._|____\__________________,-------.------------==-.____|]
 ____                    /  ##-|=======--------===-----==-|-----=|=-------------._______)
(####L-.________________/  /___|__________________________ ______|               )-------.
 \###|  ________________) `--- |---------------------===== ,_____|         _____/========"
  |##F-'              | /\ --- |         __mmmmm__________(======|...---''/
  |###/               (_\ \    |_______ ' "-L  nn [mf]    |      |
  |##|                     """"        \__________________|      |
 /##/                                   )       //((  // ||   _,-/
/##/                                   /       /\\_V_//   |,-"  (
\#/                                  ./       /  `---"     \     \
 v                                  /_       /              \     `.
                                   /_ `-.___/                \      `.
                                     `-.___/                  ".      `. -- GO 消灭 bug
                                                                ".      `.
                                                                  ".    _,"
                                                                    ".-"
                        当前springboot版本: ${spring-boot.version}

Realize the effect:

 If you want to set up Banner more easily, you can refer to this step, and you can implement a custom Banner in just one step

Customize the Banner according to the picture

The setting of Banner is very simple, friends who like it, hurry up and set it up! ! !

Guess you like

Origin blog.csdn.net/weixin_44693109/article/details/122987309