Springboot | The 23rd chapter: the Integration of log management

Source: Internet
Author: User
Tags set time java util log4j
Objective

In this series of the fourth: Log management, because the work of the log is the default configuration, nor in-depth understanding, because the deployment process directly used linux in the 输出重定向 functions, such as java -jar xx.jar > app.log 2>&1 & direct output to a log file. So there is no serious concern about the default log format. Series of articles came out, also saw a netizen feedback said how to log the relevant configuration, or the configuration failure problem. In accordance with the principle of responsibility, this article will be detailed in the next SpringBoot section of the log management related configuration issues. Also recently familiar with the next, there are shortcomings, also hope to point out!

    • A little knowledge
    • Integrated LOG4J2
      • Configuration dependencies
      • Configuration file
        • XML file Form
        • Properties File Form
        • Other formats
      • Formatting symbol Descriptions
      • Multi-environment configuration
    • Integrated Logback
      • XML form
      • Multi-Environment configuration: springprofile
      • Logback Formatting Symbols description
    • Resources
    • Summarize
    • At last
    • Cliché
A little knowledge

Before we elaborate on the configuration of each log framework, let's take a rough look at several levels of the most common logs:,,, ERROR WARN INFO DEBUG and TRACE . Like other, such as ALL , OFF and FATAL the development process should basically not be involved. So the following are common logging levels from low to high.

    • Trace: Trace. Generally on the core system performance debugging or tracking problems useful, this level is very low, generally not open, after opening the log will soon fill the disk.
    • Debug: Debugging. This people should be no strangers. The main development process is to print some of the operational information and so on.
    • Info: info. This is the most common, and most of the default is this level of logging. In general, some interactive information, some request parameters and so on are recorded. It is easy to locate the problem, or to restore the site environment. This log is relatively important.
    • WARN: Warning. This is generally a record of potential information that could cause errors. such as when the startup, a configuration file does not exist or a parameter is not set or the like.
    • Error: Wrong. This is also more common, generally in the catch exception when the output, although the error occurred, but does not affect the normal operation of the system. It can cause system errors or downtime.

If you set the log to a certain level, you can print it higher than this level . For example, set up INFO , then, and so on ERROR WARN can output print, and DEBUG , and TRACE so on is ignored.

In order to be able to support the various log frameworks well, the development process is generally used Commons Logging or SL4J these 门面 log tools. The bottom layer encapsulates the operation of the unified log, shielding the differences between different log components. When we use or switch a log frame, we simply need to introduce a dependent package to replace it without having to modify the source code. The actual operation of its final log is implemented by the like log4j2 , logback these log frameworks.

From the previous chapters, we know. , SpringBoot internal logs are also used Commons Logging , and the default configuration also provides support for common logs, such as: Java Util Logging , Log4J ,, Log4J2 and Logback . Each Logger can be configured to use the console or file to output the log content.

About the custom configuration of the log and other relevant knowledge points, here is not elaborated, can go directly to the Spring Boot | The fourth chapter: Log Management "understand." This section focuses on common log4j2 and logback related configurations.

Integrated LOG4J2

log4j2is log4j the upgrade version, claiming to have higher performance than the first version, of course, is now slowly logback replaced.

Configuration dependencies

0. Remove the Springboot default logback dependency package. Since we have introduced directly spring-boot-starter-web , we have eliminated the corresponding package directly.

Off-topic: The actual introduction spring-boot-starter-logging of the package is spring-boot-starter dependent, so we can also directly spring-boot-starter under the exclusion.

<!-- 排除logging --><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>

Or

        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter</artifactId>            <exclusions>                <exclusion>                    <groupId>org.springframework.boot</groupId>                    <artifactId>spring-boot-starter-logging</artifactId>                </exclusion>            </exclusions>        </dependency>
    1. Join the log4j2 dependency.
        <!-- 引入log4j2 -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-log4j2</artifactId>        </dependency>
Configuration file

According to the official website, the default is support XML , JSON , YAML and properties format.

XML file Form

According to Springboot's official website, we name a log4j2-spring.xml file as the default log configuration file.

Log4j2-spring.xml (This configuration is modified from: Chat LOG4J2 profile Log4j2.xml):

<?xml version= "1.0" encoding= "UTF-8"?> <!--log level and priority sorting: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > All-and <!--the status behind the configuration, which sets the information output within the LOG4J2 itself, which can be set to TRACE, You will see various detailed outputs of the log4j2 interior--<!--monitorinterval:log4j can automatically detect the configuration file and reconfigure itself, setting the interval of seconds--<configuration status= " WARN "monitorinterval=" > <!--first define all appender--> <appenders> <!--This output console configuration--and Lt;console name= "Console" target= "System_out" > <!--output log format--<patternlayout pattern= "[%d{ HH:mm:ss:SSS}] [%p]-%l-%m%n "/> </console> <!--file will print out all the information, this log every time the program will be automatically emptied, by the Append property, which is very useful, Suitable for temporary testing--<file name= "log" filename= "Log/test.log" append= "false" > <patternlayout pattern= "%d{hh: Mm:ss. SSS}%-5level%class{36}%l%M-%msg%xex%n "/> </File> <!--This will print out all info and the following levels of information, the size The log is automatically saved under a folder created by the year-month and compressed, as archived--<rolLingfile name= "Rollingfileinfo" filename= "${sys:user.home}/logs/info.log" filepattern= "${sys:user.hom E}/logs/$${date:yyyy-mm}/info-%d{yyyy-mm-dd}-%i.log "> <!--console only outputs level and above information (Onmatch), other direct rejections (ONMISMATC h)--<thresholdfilter level= "info" onmatch= "ACCEPT" onmismatch= "DENY"/> <patt Ernlayout pattern= "[%d{hh:mm:ss:sss}] [%p]-%l-%m%n"/> <Policies> <timebasedtri         ggeringpolicy/> <sizebasedtriggeringpolicy size= "MB"/> </Policies>                      </RollingFile> <rollingfile name= "Rollingfilewarn" filename= "${sys:user.home}/logs/warn.log" filepattern= "${sys:user.home}/logs/$${date:yyyy-mm}/warn-%d{yyyy-mm-dd}-%i.log" > <ThresholdFilt ER level= "warn" onmatch= "ACCEPT" onmismatch= "DENY"/> <patternlayout pattern= "[%d{hh:mm:ss:sss}] [%p]-%          L-%m%n "/>   <Policies> <TimeBasedTriggeringPolicy/> <sizebasedtriggeringpolicy size=             "MB"/> </Policies> <!--The Defaultrolloverstrategy property is not set, the default is up to 7 files in the same folder, which is set to <defaultrolloverstrategy max= "/> </RollingFile> <rollingfile name=" Rollingfi Leerror "Filename=" ${sys:user.home}/logs/error.log "filepattern=" ${sys:user.home}/logs/$${date:yyyy-m             M}/error-%d{yyyy-mm-dd}-%i.log "> <thresholdfilter level=" error "onmatch=" ACCEPT "onmismatch=" DENY "/>                 <patternlayout pattern= "[%d{hh:mm:ss:sss}] [%p]-%l-%m%n"/> <Policies> <TimeBasedTriggeringPolicy/> <sizebasedtriggeringpolicy size= "MB"/> </p Olicies> </RollingFile> </appenders> <!--then define the logger, only the appender,appender that are defined logger and introduced will take effect -&LT;LOGGERS&GT          <!--filter out some of the useless debug information for spring and MyBatis--<logger name= "org.springframework" level= "INFO" ></logger> <logger name= "Org.mybatis" level= "info" ></logger> <!--the custom package is set to info, you can see that the output log does not contain the debug output --<logger name= "cn.lqdev.learning" level= "INFO"/> <root level= "All" > <appe Nder-ref ref= "Console"/> <appender-ref ref= "Rollingfileinfo"/> <appender-ref ref= "roll Ingfilewarn "/> <appender-ref ref=" Rollingfileerror "/> </root> </loggers> < /configuration>

I think this configuration step is: First configuration appenders , according to the needs of personalized configuration, such as Day records, and so on, then you can use the logger personalized configuration of some package level log level, the last configuration root appender .

Properties File Form

It is noted from the official website that the support for the configuration file is available from the 2.4 release, which should be used with caution. Detailed use of the syntax can be viewed on the official website: Configuration with the Properties, here the official website of the example of the following simple:

# LOG4J2 Internal log level status = error# configuration log information output to: Err is indicated as a standard error output, can also be a file path or a urldest = err# configuration name = propertiesconfig# Custom attribute names for use in subsequent configurations, such as ${filename} property.filename = Target/rolling/rollingtest.log # level filtering (filtering logging) Filter.threshold.type = thresholdfilter# logs above debug level only, case can be filter.threshold.level = debug# Console type log output source Appender.console.type = console# Name: Unique Appender.console.name = stdout# layout type Appender.console.layout.type = Patternlayout # Output Template format this is Springbootappender.console.layout.pattern =%d{yyyy-mm-dd HH:mm:ss. SSS}-%5p ${pid:-} [%15.15t]%c{1.} [%t]:%m%n# Filter Level Thresholdfilter: output below level Appender.console.filter.threshold.type = thresholdfilter# The logging level appender.console.filter.threshold.level = info # Scrolls the file and automatically generates a new file based on the configuration such as file size or time Appender.rolling.type = RollingFileappender.rolling.name = rollingfile# log file name Appender.rolling.fileName = ${filename}# File naming rules for log rollback Appender.rolling.filePattern = target/rolling2/test1-%d{mm-dd-yyyy}-% I.log.gzappender.rolling.layout.type = patternlayout# output format appEnder.rolling.layout.pattern =%d%p%c{1.} [%t]%m%n# the policy of rolling logs, that is, setting when to create a new log file output log Appender.rolling.policies.type = policies# set time Appender.rolling.policies.time.type = timebasedtriggeringpolicy# Specifies how long the unit scrolls once units follow the Filepattern configuration accuracy last one, This is 2 seconds. appender.rolling.policies.time.interval = 2appender.rolling.policies.time.modulate = true# log file size Appender.rolling.policies.size.type = sizebasedtriggeringpolicy# To test the settings a little bit appender.rolling.policies.size.size=1kb # # There are other trigger conditions such as: Crontriggeringpolicy the specific use of the cron expression can be self-search # Specify the same folder with a maximum of a few log files when you start to delete the oldest, Create a new Appender.rolling.strategy.type = defaultrolloverstrategy# up to 5 files, actually still look at the value of Filepattern I, when greater than 5, will automatically overwrite the Appender.rolling.strategy.max = 5 Rootlogger.level = InforootLogger.appenderRef.stdout.ref = stdout

Here you need to set the profile property value ( logging.config ), local test, the directory rolling will generate files, but the inside is empty. Plus, it's normal:

logging.config=classpath:log4j2.properties

Off-topic: After Setup, the properties configuration rules are still not well understood. Feel how to match as if you can output, but also hope that there are users can share the specific configuration rules. After the comparison, still feel that the xml format is more intuitive and easy to understand.

Other formats

According to the official website, you can also json yml cooperate with the format, but need to join the corresponding dependency.

format Dependency Packages file name
Yaml com.fasterxml.jackson.core:jackson-databindcom.fasterxml.jackson.dataformat:jackson-dataformat-yaml log4j2.yamllog4j2.yml
Json com.fasterxml.jackson.core:jackson-databind log4j2.jsonlog4j2.jsn

Add the appropriate dependency package as needed. There is no detail here.

Formatting symbol Descriptions

For formatted output, you will see that there are different formatting symbols, at first looked at is also confused, the following search related data after a simple collation summarized under.

Off topic: SpringBoot The default log4j2 configuration file is in: spring-boot-1.5.15.RELEASE.jar/org/springframework/boot/logging/log4j2/log4j2.xml .

Specific official website has the description: Http://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout

######### common Parameters #########//%c{parameter} or%logger{parameter} # #输出日志名称%c{parameter} or%class{parameter # #输出类型%d{parameter} time zone te{parameter} time zone} # #输出时间, such as:%d{yyyy-m  M-dd HH:mm:ss, Sss}%f|%file # #输出文件名highlight {pattern}{style} # #高亮显示%l # #输出错误的完整位置%l # #输出错误行号%m or%msg or %message # #输出错误信息%m or%method # #输出方法名%n # #输出换行符%level{parameter 1}{parameter 2}{parameter 3} # #输出日志的级别%t or%thread # #创建lo Gging the thread name of the event */######### special symbol ############ #有些特殊符号不能直接打印, you need to use the entity name or number//&--&amp;  Or & #38;<--&lt;  Or & #60;>--&gt; or & #62; "--&quot; or & #34; '--&apos; or & #39; */######## pattern Alignment decoration ##########//The alignment adornment, you can specify the output format of the information, such as whether left-justified, whether blank, and so on. # # Write the format to add a decimal between any pattern and%, which can be positive or negative. # # integers for right alignment, negative numbers for left alignment, # # integer digits represent the minimum n characters of the output information, if the output information is not enough n characters, will be filled with spaces; # # decimal indicates the maximum number of characters for the output information, if more than n characters, only the last n characters of the information # # (Note: Retain the last 20 characters, not the first 20 characters) */#示例如下//%20--right, less than 20 characters in front of the information with a space, more than 20 characters to retain the original information%-20--left-aligned, less than 20 characters in the information behind with a space to complement, More than 20 characters retain the original information%.30--if the information exceeds 30 characters, only the last 30 characters%20.30--right-aligned, less than 20 characters are filled with spaces before the information, and more than 30 characters are reserved for the last 30 characters%-20.30--left-aligned, less than 20 characters after the information with a space to fill, more than 30 characters will only retain the last 30 characters 
Multi-environment configuration

The values can be set directly through the multi-environment configuration file, logging.config such as
Application-test.properties

logging.config=classpath:log4j2-test-spring.xml

Application-prod.properties

logging.config=classpath:log4j2-prod-spring.xml
Integrated Logback

logbackis another open source log component designed by the LOG4J founder. It is also SpringBoot the default logging framework.

XML form

Since the default is to use logback , so only need to configure a logback-spring.xml file in the resources directory, it will be automatically recognized.

Logback-spring.xml (modified from: Logback.xml detailed):

<?xml version= "1.0" encoding= "UTF-8"? ><configuration debug= "false" > <!--define the storage address of the log file do not Logback The configuration uses a relative path--<property name= "Log_home" value= "/Home"/> <!--console output---<appender name= "STDOUT "class=" Ch.qos.logback.core.ConsoleAppender "> <encoder class=" ch.qos.logback.classic.encod Er.            Patternlayoutencoder "> <!--formatted output:%d for date,%thread for thread name,%-5level: Level shows 5 character width from left%msg: Log message,%n is line break-- <pattern>%d{yyyy-mm-dd HH:mm:ss. SSS} [%thread]%-5level%logger{50}-%msg%n</pattern> </encoder> </appender> <!--by daily life Chengzhi file--<appender name= "file" class= "Ch.qos.logback.core.rolling.RollingFileAppender" > <rol            Lingpolicy class= "Ch.qos.logback.core.rolling.TimeBasedRollingPolicy" > <!--log file output file name-- <filenamepattern>${log_home}/testokong.log.%d{yyyy-mm-dd}.log </filenamepattern&Gt             <!--log file retention days-<MaxHistory>30</MaxHistory> </rollingPolicy> <encoder class= "Ch.qos.logback.classic.encoder.PatternLayoutEncoder" > <!--formatted output:%d for date,%thread for thread name,%- 5level: Level shows 5 character width from left%msg: Log message,%n is a newline character---<pattern>%d{yyyy-mm-dd HH:mm:ss.        SSS} [%thread]%-5level%logger{50}-%msg%n</pattern> </encoder> <!--The maximum size of the log file-- <triggeringpolicy class= "Ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy" > <maxfiles Ize>10mb</maxfilesize> </triggeringPolicy> </appender> <!--The custom package is set to info, you can see the output log is not packet With debug output--<logger name= "cn.lqdev.learning" level= "INFO"/> <!--log output level--<root level= "INFO" > <appender-ref ref= "STDOUT"/> <appender-ref ref= "FILE"/> </root></config Uration>
Multi-Environment configuration: springprofile

Use extended attributes springProfile with springProperty the logback-spring.xml effect of having the configuration implement a multi-environment configuration.

    <!-- 生产环境生效 -->    <springProfile name="prod">        <root level="error">            <appender-ref ref="STDOUT" />            <appender-ref ref="FILE" />        </root>    </springProfile>    <!-- 测试和开发环境日志级别为INFO/并且记录日志文件 -->    <springProfile name="dev,test">        <!-- 日志输出级别 -->        <root level="INFO">            <appender-ref ref="STDOUT" />            <appender-ref ref="FILE" />        </root>    </springProfile>

springProfileRead property values are also supported Spring Environment

<!-- 读取 spring.application.name 属性来生成日志文件名    scope:作用域    name:在 logback-spring.xml 使用的键    source:application.properties 文件中的键    defaultValue:默认值 --><springProperty scope="context" name="logName" source="spring.application.name" defaultValue="myapp.log"/>

You can then use it ${logName} to get the value of the variable directly.

Logback Formatting Symbols description

and log4j2 similar, specific to the official website to view: Patternlayout.

    • %M: The message specified in the output code
    • %p: Output priority, i.e. Debug,info,warn,error,fatal
    • %r: The number of milliseconds to output the log information from the application boot to output
    • %c: The class that the output belongs to, which is usually the full name of the class
    • %t: Output The name of the thread that generated the log event
    • %n: Output a carriage return line break, Windows platform is "\ r \ n", Unix platform is "\ n"
    • %d: the date or time of the output log time, the default format is ISO8601, can also be specified after the format, such as:%d{yyy MMM dd hh:mm:ss,sss}, output similar: October 18, 2002 22:10:28,921
    • %l: The location where the output log event occurs, including the class name, the thread that occurred, and the number of rows in the code. Example: Testlogback.main (testlogback.java:10)

Off topic: SpringBoot The default Logback configuration file is in: spring-boot-1.5.15.RELEASE.jar/org/springframework/boot/logging/logback/defaults.xml .

Resources

For detailed property configuration, you can search by yourself. The following are some of the site information that is referenced when writing this article.

    1. docs.spring.io/spring-boot/docs/1.5.15.release/reference/htmlsingle/#boot-features-logging

    2. Http://logging.apache.org/log4j/2.x/manual/configuration.html

    3. Www.cnblogs.com/wang1024/p/7786916.html

    4. http://blog.51cto.com/11931236/2058708

    5. Www.cnblogs.com/hafiz/p/6170702.html

    6. logback.qos.ch/manual/

Summarize

This paper mainly introduces the log-related knowledge points, and introduces the common log4j2 and logback related configuration briefly. For detailed configuration information, you can go to the official website. In addition, for the log, not the more the better, after all, the log output will have performance corruption. Individuals are advised to record this record, to keep the site of the accident and some errors are required to be logged. And like some meaningless output, itself is superfluous. Finally, don't hit the log at random! When printing the log, also note that you cannot use string concatenation, you need to use placeholders or judge the log level first! Don't let the logs slow down your system! in the next chapter, we will mainly introduce the use AOP of unified access log management.

At last

At present, many big guys on the internet have a SpringBoot series of tutorials, if there is a similar, please forgive me. This article is the author in front of the computer word knocking, each step is his own practice and understanding. If there is something wrong in the text, also hope to put forward, thank you.

Cliché
    • Personal QQ:499452441
    • Public Number:lqdevOps

Personal blog: http://blog.lqdev.cn

Complete Example: github.com/xie19900123/spring-boot-learning/tree/master/chapter-23

Original Address:/HTTP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.