Spring Boot Log Framework Practice-technology sharing for HANSONWANG99

Source: Internet
Author: User
Tags java util log4j
This article is mainly for you to share about the Spring boot log Framework practice, the Code section is also very detailed, the need for small partners to refer to.

Overview

In Java applications, logs are generally divided into the following 5 levels:

    • Error message

    • WARN warning message

    • Info General Information

    • Debug Debugging Information

    • Trace Trace Information

Spring Boot uses Apache's commons logging as the internal log framework, which is simply a log interface that needs to be specified for this interface in the actual application.

SPRINGBT The default log implementation is the Java Util Logging, is the JDK's own log package, in addition SPRINGBT of course support log4j, logback such a popular log implementation.

Unify the above log implementations collectively as the log framework

Now let's practice!

Using the spring Boot logging plugin

    • First, configure the Application.properties file:

Logging.level.root=info
    • The Controller section 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";    }}
    • Run results

Because the log level is set to info, log information that contains info and above levels will be printed

As you can see, most of the info logs come from the SPRINGBT framework itself, and 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 the specific package in your app to the debug level log so you can see only the debug and above levels of logs in the package you care about.

    • Control the log level for a specific package

Application.yml in the Change configuration

Logging: Level  :    root:error    Com.hansonwang99.controller:debug

Obviously, set the root log level to error, and then set com.hansonwang99.controller the log level of the package to debug, which is to prevent all of the individual setup methods from being allowed

    • 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";    }}
    • Run results

The info-level logs of the frame itself are all hidden, and the logs in the specified package are printed smoothly by level

    • Output the log to a 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 was output to a file, the console would still print a copy of it, which was found to be org.slf4j.Logger unable to solve the problem.

Integrated LOG4J Log Framework

    • adding 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>
    • Add a file under the Resources directory log4j2.xml , as follows:

<?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>
    • All other code remains the same

Running the program Discovery Console does not have the log output, and the contents of the Hello2.log file are in line with our expectations:

and match the log format and the pattern="%d{HH:mm:ss,SSS} %p %c (%L) - %m%n" format defined in the

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>
    • Log4j2.xml Configuration

<?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.g  Z "> <Filters> <thresholdfilter level=" INFO "/> <thresholdfilter            Level= "WARN" onmatch= "DENY" onmismatch= "NEUTRAL"/> </Filters>  <patternlayout pattern= "[%d][%t][%p][%c:%l]%m%n"/> <Policies> <!--archive daily files -<Timebasedtriggeringpolicy interval= "1" modulate= "true"/> <!--limit individual file size--<siz Ebasedtriggeringpolicy size= "2 MB"/> </Policies> <!--limit number of files per day--<de Faultrolloverstrategy compressionlevel= "0" max= "/> </RollingFile> <rollingfile name=" ROLLINGF Ilewarn "Filename=" ${log_path}/warn.log "filepattern=" ${LOG_PATH}/$${DATE:YYYY-MM}/WARN-%D{YYYY-MM-DD} -%i.log.gz "> <Filters> <thresholdfilter level=" WARN "/> <thresh Oldfilter level= "ERROR" onmatch= "DENY" onmismatch= "NEUTRAL"/> </filters&            Gt <patternlayout pattern= "[%d][%t][%p][%c:%l]%m%n"/> <Policies> <!--archive daily files--&G                T          <timebasedtriggeringpolicy interval= "1" modulate= "true"/> <!--limit a single file size--      <sizebasedtriggeringpolicy size= "2 MB"/> </Policies> <!--limit the number of files per day- <defaultrolloverstrategy compressionlevel= "0" max= "ten"/> </RollingFile> <rollingfile N Ame= "Rollingfileerror" filename= "${log_path}/error.log" filepattern= "${log_path}/$${date:yyyy-mm}/erro R-%d{yyyy-mm-dd}-%i.log.gz "> <thresholdfilter level=" ERROR "/> <patternlayout pattern=" [ %d][%t][%p][%c:%l]%m%n "/> <Policies> <!--archiving daily files--<timeba Sedtriggeringpolicy interval= "1" modulate= "true"/> <!--limit individual file size--<sizebased Triggeringpolicy size= "2 MB"/> </Policies> <!--limit number of files per day--<defaultr        Olloverstrategy compressionlevel= "0" max= "ten"/> </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>
    • Controller code:

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";}    }
    • Run results

Logs are stored in different files according to different levels, the log file size of more than 2M will be divided into multiple files compressed storage, production environment of the journal file size is recommended to adjust to 20-50MB.

Postscript

Author more original articles see SF column

Author more SPRINGBT Practice articles in this:

    • The practice of Elasticsearch search engine in Springboot

    • Preliminary study on Kotlin+springboot joint programming


Related recommendations:

8 Java Log Frameworks most commonly used by Java programmers

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.