Springboot Log Management

Source: Internet
Author: User
Tags java util log4j

The Spring boot internal log system uses the Commons Logging, but the underlying log implementation is open. The default support for Java Util Logging, Log4j,log4j2, and Logback provides configuration. In each case, the console output is preconfigured and optional file output can be used.

The default log output format for Spring boot is as follows:

2014-03-05 10:57:51.112 INFO 45469---[main] org.apache.catalina.core.Sta
ndardengine:starting Servlet Engine:apa Che tomcat/7.0.52
2014-03-05 10:57:51.253 INFO 45469---[ost-startstop-1] o.a.c.c.c.[tomcat].[ Localhos
T]. [/]: Initializing Spring embedded webapplicationcontext
2014-03-05 10:57:51.253 INFO 45469---[ost-startstop-1] O.s . Web.context.ContextLoade
r:root Webapplicationcontext:initialization completed in 1358 Ms
2014-03-05 10:57:51.698 INFO 45469---[ost-startstop-1] o.s.b.c.e.servletregistratio
nbean:mapping servlet: ' Dispatcherservlet ' to [/]
2014-03-05 10:57:51.702 INFO 45469---[ost-startstop-1] O.s.b.c.embedded.filterregis
trationbean:mapping filter: ' Hiddenhttpmethodfilter ' to: [/*]

The output nodes (items) are as follows:
1. Date and time-accurate to millisecond, and easy to sort.
2. Log level-ERROR, WARN, INFO, DEBUG or TRACE.
3. Process ID.
4. A---Separator that distinguishes the beginning of the actual log information.
5. Thread name-included in square brackets (the console output may be truncated).
6. Log name-usually the class name (abbreviation) of the source class.
7. Log information.

log file output by default, Spring boot logs only the log to the console and does not write to the log file. If you want to write to the log file except for the output to the console, you need to set the Logging.file or Logging.path attributes (for example, in your application.properties). The following table shows how to use logging.* in combination:

Logging.file Logging.path Example Describe
(none) (none) Log to console only
Specific file (none) My.Log Written to a specific log file, the name can be a fine
The exact position or relative to the current directory
(none) Specific
Folder
/var/log Write is to a special definite precise piece of the clamping position or the S phase p to Rin in G.l when OG before, record name can

Log files are rotated (split) every 10M, and, like the console, defaults record the ERROR, WARN, and info level information.
Log LevelAll supported log systems are in spring's environment (for example, in application.properties) through ' logging.level.*=level ' (' Level ' is Trace, DEBUG, INFO, WARN, ERROR, FATAL,
Off one of the log levels set.
Example: Application.properties
Logging.level.org.springframework.web=debug
Logging.level.org.hibernate=error
Custom Log ConfigurationYou can activate a variety of logging systems by adding the appropriate libraries to the classpath. Then at the root of the classpath (root) or through the spring environment The location specified by the Logging.config property provides a suitable configuration file for further customization (note that since the log was initialized before ApplicationContext was created, it is not possible in spring's @configuration file to Control logs through @propertysources. System Properties and the usual spring boot external configuration file work correctly. Depending on your log system, the following files will be loaded:
Log system Custom
Logback Logback.xml
Log4j Log4j.properties or Log4j.xml
Log4j2 Log4j2.xml
JDK (Java Util Logging) Logging.properties

To help customize some of the other properties, transition from Spring's envrionment to System properties:
Spring Environment System Property Evaluation
Logging.file Log_file If defined, use in the default log configuration
Logging.path Log_path If defined, use in the default log configuration
Pid Pid Current processing process ID (if it can be found and not yet defined as an operating system environment variable)

All supported log systems can query system properties when parsing their configuration files. You can refer to the default configuration in Springboot.jar.
Note: The Java Util Logging has class loading problems while running the executable jar, and we recommend that you avoid using it as much as possible.
Case StudySpringboot Web Launcher By default is Logback, people on the Internet to test the best performance or LOG4J2, so the following simple introduction log4j2 under the Springboot under the configuration 1. First, remove the Spring-boot-starter-web and the spring-boot-starter-logging below the Spring-boot-starter package, The SPRING-BOOT-STARTER-LOG4J2 package is then introduced.
<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>

 <!--https://mvnrepository.com/ artifact/org.springframework.boot/spring-boot-starter-log4j2-->
<dependency>
   <groupid >org.springframework.boot</groupId>
   <artifactid>spring-boot-starter-log4j2</artifactid >
</dependency>
Add Log4j2.xml to src/main/resources under Resource folders
<?xml version= "1.0" encoding= "UTF-8"?> <!--configuration's status is set to the LOG4J2 framework itself log level--> < Configuration status= "Warn" packages= "Com.example.springboot" > <!--all < Trace < Debug < Info < warn & Lt Error < Fatal < off--> <!--The program prints a log that is above or equal to the set level, and the higher the log level, the fewer logs are printed. Off: The highest level, used to turn off all logging. --> <Properties> <property name= "filename" >logs/springboot</Property> <property name= " Pattern ">%d{yyyy-mm-dd HH:mm:ss. SSS} |-%-5level [%thread]%c [%l]-| %msg%n</property> </Properties> <!--<filter type= "Thresholdfilter" level= "Trace"/>--> --the level set in Appenders is the log levels of the project you are developing--> <Appenders> <console name= "STDOUT" > <thresholdfilter level= "
			Info "onmatch=" ACCEPT "onmismatch=" DENY "/> <PatternLayout> <Pattern>${pattern}</Pattern> </PatternLayout> </console> <rollingfile name= "Rollingfileinfo" Filename= "${filename}_info.Log "filepattern=" ${filename}_%d{yyyy-mm-dd dd}_info_%i.log "> <thresholdfilter level=" info "onMatch=" ACCEPT " Onmismatch= "DENY"/> <PatternLayout> <Pattern>${pattern}</Pattern> </patternlayout&gt
			; <Policies> <timebasedtriggeringpolicy interval= "1"/> <sizebasedtriggeringpolicy size= "1000 KB"/&G
			T </Policies> <defaultrolloverstrategy max= "/> </RollingFile> <rollingfile name=" Rollingfile Error "Filename=" ${filename}_error.log "filepattern=" ${filename}_%d{yyyy-mm-dd Dd}_error_%i.log "> < Thresholdfilter level= "error" onmatch= "ACCEPT" onmismatch= "DENY"/> <PatternLayout> <pattern>${p 
				attern}</pattern> </PatternLayout> <Policies> <timebasedtriggeringpolicy interval= "1"/> 
		<sizebasedtriggeringpolicy size= "1000 KB"/> </Policies> <defaultrolloverstrategy max= "/>"
</RollingFile>		<rollingfile name= "Rollingfilewarn" filename= "${filename}_warn.log" filepattern= "${filename}_%d{yyyy-MM-dd dd}_" 
				Warn_%i.log "> <thresholdfilter level=" Warn "onmatch=" ACCEPT "onmismatch=" DENY "/> <PatternLayout> <Pattern>${pattern}</Pattern> </PatternLayout> <Policies> <!--timebasedtriggeri Ngpolicy This configuration needs to be used in conjunction with Filepattern, note that the file rename rule configured in Filepattern is ${file_name}-%d{yyyy-mm-dd hh-mm}-%i, the smallest time granularity is MM, that is, minutes, The size specified by Timebasedtriggeringpolicy is 1, which is combined to generate a new file every 1 minutes. If changed to%d{yyyy-mm-dd HH}, the minimum granularity is hours, then a file is generated every one hours--> <timebasedtriggeringpolicy interval= "1"/> <!--log file exceeds the point Fixed size rebuild configuration file, can set unit contains KB, MB or GB--> <sizebasedtriggeringpolicy size= "1000 KB"/> </Policies> < !--the parameter Max in Defaultrolloverstrategy, you can limit the size in Sizebasedtriggeringpolicy to only the Max archive--> <
		Defaultrolloverstrategy max= "/> </RollingFile> <file name=" File "filename=" ${filename}.log ">	<thresholdfilter level= "Info" onmatch= "ACCEPT" onmismatch= "DENY"/> <PatternLayout> <pattern&gt ;${pattern}</pattern> </PatternLayout> </File> </Appenders> <!--logger and root level attributes are used to set Semantic log level, but if the level set here is lower than the Thresholdfilter property inside the Appender, the levels set by Thresholdfilter are the same, and if Root is set all logs are output, is smaller than the info set in the file's Thresholdfilter, the level of the actual output to the log file is the info level, and if the level of logger and root is defined higher than the Thresholdfilter setting, 
		The log level defined for logger and root levels is the same. To put it simply, who is high and who is the--> <Loggers> <!--logger is used to specify the log output location for a particular package--> <!--additivity is used to set whether to continue passing log content, false means not to pass, T Rue means that the STDOUT console output is configured for delivery--> <!--logger and root, when logger is set to False The logs in the controller package will only be based on the output error of logger set and the above level log. If set to true, he will pass the logger set output error and above level of log again to root again output again. --> <logger name= "Com.example.springboot.controller" level= "error" additivity= "false" > <appender-ref r ef= "STDOUT"/> </Logger> <root level= "All" > <!--if the ST is not set in RootDout Console output log, all exception of the project will not be output in the console unless you manually capture the exception Logger.error output to print information, but encounter run-time exceptions, you can not be caught in advance of the console print exception information, So the development environment still write this better--> <appender-ref ref= "STDOUT"/> <appender-ref "File" ref=/>
		"Rollingfileinfo"/> <appender-ref ref= "Rollingfileerror"/> <appender-ref ref= "RollingFileWarn"/> </Root> </Loggers> </Configuration>


configure different log profile methods to be used in different environments:First, create 2 log profiles for different environments, such as: Log4j2-dev.xml,log4j2-test.xml,log4j2-pro.xml and then the main configuration file in Springboot, If you configure Logging.config=classpath:log4j2-dev.xml in Application.properties, you can use the dev-configured log file
Asynchronous Log Environment configurationFirst you need to introduce in POM
<dependency>
	<groupId>com.lmax</groupId>
	<artifactid>disruptor</artifactid >
	<version>3.3.4</version>
</dependency>

In the Application startup class, add the code for the Red section:
public static void Main (string[] args) {
    	system.setproperty ("Log4jcontextselector", " Org.apache.logging.log4j.core.async.AsyncLoggerContextSelector ");
        Springapplication.run (Application.class, args);
}
The Log4j2.xml configuration is as follows (only as a case)
<?xml version= "1.0" encoding= "UTF-8"?>
<!--Don ' t forget to set system property-dlog4j2.contextselector= Org.apache.logging.log4j.core.async.AsyncLoggerContextSelector to make all 
	loggers asynchronous.-->
<configuration status= "WARN" >
	<Appenders>
		<!--Async loggers'll auto-flush in batches Switch off Immediateflush. -->
		<randomaccessfile name= "Randomaccessfile" filename= "Logs/async.log"
			immediateflush= "false" Append= "false" >
			<PatternLayout>
				<pattern>%d%p%c{1.} [%t]%m%ex%n</pattern>
			</PatternLayout>
		</RandomAccessFile>
	</Appenders>
	<Loggers>
		<root level= "info" includelocation= "false" >
			<appenderref ref= " Randomaccessfile "/>
		</Root>
	</Loggers>
</Configuration>
The official document has a message to note when Asyncloggercontextselector is used to make all loggers asynchronous, make sure to use
Normal <root> and <logger> elements in the configuration. The Asyncloggercontextselector would
Ensure that all loggers are asynchronous, using a mechanism this is different then what when
You configure <asyncRoot> or <asyncLogger>. The latter elements are intended for mixing async
With Sync loggers. If you use both mechanisms together the background threads with two
Where your application passes the "log message to thread A, which passes" to thread B,
which then finally logs to disk. This works, but there'll be a unnecessary step in the
Middle.

You need to understand the specific use of configuration properties can refer to this blog content: https://www.cnblogs.com/hafiz/p/6170702.html

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.