Refer to the Spring Boot Official document log section
Spring boot by default when using "starters" to output logs using Logback
, including appropriate Logback routing, to ensure that other log frameworks (Java Util Logging, Commons Logging, log4j, slf4j) are working properly
The 26.5 custom log configuration section of the Sping boot document explains the method for customizing the logs
A variety of log systems can be
- Add the appropriate Log framework library to Classpath
- The appropriate configuration profile is added to the root directory of the classpath or other local directory, using the spring configuration
loggin.config
configuration to specify the configuration file
Relies on the log framework chosen by the developer. These corresponding configuration files will be loaded
Log Frame |
configuration file |
Logback |
logback-spring.xml , logback-spring.groovy , logback.xml ,logback.groovy |
Log4j2 |
log4j2-spring.xml ,log4j2.xml |
JDK (JAVA Util Logging) |
logging.properties |
Introducing the LOG4J2 Log framework
The log4j2 is not introduced. LOG4J2 official website
Configuration of the scheme in Official document 77.2 Configure log4j for Logging
1. Maven Dependency Configuration
pom.xml
Remove Logback and introduce log4j2
<!-- 节选 --><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>
2. Configuration files
2.1 Log4j2.xml
Using an XML format configuration file eliminates the need to add additional dependent libraries.
2.2 Log4j2.yaml/log4j2.yml
Use the YAML/YML format configuration file. Need to introduce additional dependent libraries
<!-- 解析yml配置 --><dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId></dependency><dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId></dependency>
2.3 Log4j2.json
Using a JSON-formatted configuration file requires additional dependency libraries to be introduced
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId></dependency>
3. Modify the Spring boot configuration
Specifying the spring boot configuration file
application.yaml
The file is configured as follows
logging: config: classpath:log4j2.xml
LOG4J2 Log Configuration
For detailed configuration of LOG4J2, access to official documentation
Overview
About the basic information about LOG4J2.
The level of the log is divided into:
- Trace (Trace)
- Debug (Debug)
- Info (info)
- Warn (warning)
- Error (Errors)
- Fatal (Critical error)
Here is a log method that bloggers often useRollingFileAppender
Take a specific configuration as an example
<?xml version= "1.0" encoding= "UTF-8"? ><configuration status= "Trace" strict= "true" Name= "LogConfig" > < properties> <property name= "filepath" >/tmp/log4j2</Property> </Properties> <appenders > <console name= "STDOUT" target= "System_out" > <PatternLayout> <pattern& Gt [%d]-[%c]-[%highlight{%level}]-[%method]-[%t]-%msg%n</pattern> </PatternLayout> &L t;/console> <rollingfile name= "Logservice" filename= "${filepath}/logservice.log" filepattern= "${filepath}/bak/logservice-%d{yy-mm-dd hh:mm:ss}.log.gz" > <PatternLayout> <PATTERN>[%D]-[%c]-[%highlight{%level}]-[%method]-[%t]-%msg%n</pattern> </ patternlayout> <Policies> <crontriggeringpolicy schedule= "1 * * * * *?" Evaluateonsta Rtup= "true"/> </Policies> </RollingFile> </Appenders> <Loggers> <logger name= "Filelo Gger "level=" Debug "additivity=" false "> <appenderref ref=" logservice "/> <appenderref ref = "STDOUT"/> </Logger> <root level= "Trace" > <appenderref ref= "STDOUT"/> </Root> </Loggers></Configuration>
1. Configuration Parameters
status
: Level enumeration type, control output log4j event information, default error
name
: Configuration Name
strict
: Whether to use strict XML format. Recommended use, Specification developer configuration, not support JSONP configuration
- ... Several other configurations can refer to the official documentation
2. Properties
Sets the parameter variables for the global configuration file. Used to reduce the number of duplicate encodings for custom configuration information.
<Properties> <Property name="filepath">/tmp/log4j2</Property></Properties>
Configuration context, you can use ${filepath}
to replace the/tmp/log4j2
3. Appenders
LOG4J2 offers a wealth of appender
- Asyncappender setting appender Asynchronous output log
- Cassandraappender output to Cassandra Storage
- Consoleappender Output Control Console
- Failoverappender Setting Appender Error retry
- Fileappender Output to File
- Flumeappender output to Flume
- Jdbcappender relational database tables for output to JDBC connections
- JMS Appender output to message service
- Jpaappender output to a relational row database using JPA connections
- Httpappender output to HTTP Service
- Kafkaappender output to Kafka
- Memorymappedfileappender Output to Memory
- Nosqlappender Output to NoSQL database
- Outputstreamappender file/socket Types of Appender
- Randomaccessfileappender performance is 0.2-twice times of Fileappder
- Rollingfileappender output to a file, files can be packaged according to the rules
- Rollingrandomaccessfileappender Ibid.
- Smtpappender Message form Output
- Socketappender Socket Mode Send log
The more commonly used in the project is the ConsoleAppender
and RollingFileAppender
.
The following is a description of the Appender configuration parameters described above
<Appenders> <!--consoleappender <!--name Appender--<!--target enum (system_out, SY Stem_err). Default System_out---<console name= "STDOUT" target= "System_out" > <!--output format detailed configuration see below--<PA Tternlayout> <pattern>[%d]-[%c]-[%highlight{%level}]-[%method]-[%t]-%msg%n</pattern> </PatternLayout> </Console> <!--Rollingfileappender-<!--fileName output problem name, using absolute path Ensure that the log location is correct, and that the directory has process user writable permissions-<!--filepattern log rollback file naming rules--<rollingfile name= "Logservice" Filename= "${filepath}/logservice.log" filepattern= "${filepath}/bak/logservice-%d{yy-mm-dd HH:mm: Ss}.log.gz "> <PatternLayout> <pattern>[%d]-[%c]-[%highlight{%level}]-[%method]-[% T]-%msg%n</pattern> </PatternLayout> <Policies> <!--rollback files by cron timed tasks-- <! ---Schedule cron expression--<!--evaluateonstartup (rule: When starting, check to determine the last modification time of the target file, if the cron rule determines that the file needs to be rolled back, roll back the file directly.) Start the rule action-<crontriggeringpolicy schedule= "1 * * * *?" evaluateonstartup= "true"/> </policie S> </RollingFile></Appenders>
3.2 Log Output Rule Layouts
Layout has multiple format outputs
- Csv
- Gelf
- Html
- Json
- Pattern
- ....
The project typically uses pattern-by-line output-by-item information, configured as follows:
<!-- 节选配置 --><PatternLayout> <Pattern>[%d] - [%c] - [%highlight{%level}] - [%method] - [%t] - %msg%n</Pattern></PatternLayout>
%
+ char/word
represents an output of information or format
Time%d/%date
format |
Output |
%d,%d{default} |
2012-11-02 14:34:02,781 |
%d{unix} |
1351866842 |
%d{unix_millis} |
1351866842781 |
%d{yyyy-mm-dd Hh:mm:ss,sss} |
2012-11-02 14:34:02,781 |
Class%c/%logger
The class name of the output call
%c{number}, the length of the control type
Level%level
Output level TRACE, DEBUG, INFO, WARN, ERROR, FATAL
Color Format%highlight
%HEIGHLIGHT{XXX}
XXX will be color-style, and level-related, generally used for debug debugging information
Log content%m/%msg/%message
To add text styles
Line break%n
The user journal wraps according to the output of the operating system with a different newline identifier, so it's best not \n
to use, \r\n
such as line break symbols
There are many other symbols, refer to official documents
4. Loggers
- Must contain an
Root
element, without setting the Root
element, will default to a configuration similar to the following
<Root level="error"> <AppenderRef ref="Console" /></Root>
- Configure other developers to customize the
Logger
<Loggers> <!-- name 必填且唯一 --> <!-- level 设置输出最低级别 默认error --> <!-- additivity 是否在父Logger输出, 默认 true --> <Logger name="fileLogger" level="debug" additivity="false"> <!-- 上文中定义的Appender name --> <AppenderRef ref="logService"/> <AppenderRef ref="STDOUT"/> </Logger> <Root level="ERROR"> <AppenderRef ref="STDOUT"/> </Root></Loggers>
Using logger
Take demo as an example
package info.chiwm.log4j2.service;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.springframework.stereotype.Service;/** * @author [email protected] * @ClassName: Log4j2ServiceImpl * @Description: * @date 2018/1/4 上午11:10 */@Servicepublic class Log4j2ServiceImpl implements Log4j2Service { // 使用LogManager获取配置Logger private static Logger logger = LogManager.getLogger("fileLogger"); @Override public void info(String msg) { // 输出日志 // 特别注意 不要使用 `+` 去拼接信息, 这样在控制输出级别之后, 有些日志操作不会打印, 但是它去操作了新字符串创建, 使用 `{}` 去代替 `+` logger.info("info {}", msg); } @Override public void error() { logger.error("error"); } @Override public void warn() { logger.warn("warn"); } @Override public void debug() { logger.debug("debug"); } @Override public void trace() { logger.trace("trace"); }}
Summarize
The previous configuration steps, configuration, and use steps, presumably describe the use of log4j2.
Comment Areas are welcome to indicate errors or to discuss related issues
Spring Boot + log4j2 Log Framework configuration (Maven)