By default, Spring Boot uses “Starters” to log Logback, including the appropriate Logback routing to ensure that other Logging frameworks (Java Util Logging, Commons Logging, Log4j, SLF4J) can be used normally
The 26.5 Custom Log Configuration section of the Sping Boot document describes the Custom Log Configuration method
Various logging systems can be passed
- Add the appropriate logging framework libraries to your classpath
- Add the appropriate configuration files to the root directory of the classpath or another local directory, using Spring configuration
loggin.config
Configure the specified configuration file
Depends on the logging framework chosen by the developer. The corresponding configuration files will be loaded
Logging framework configuration file Logbacklogback – spring. XML, logback – spring. Groovy, logback. XML, logback. GroovyLog4j2log4j2 – spring. XML, log4j2. XmlJDK ( JAVA Util Logging)logging.properties
Introduce the Log4j2 logging framework
I’m not going to tell you what the Log4j2 is.
Log4j2 website
Configure Log4j for Logging
1. Configure Maven dependencies
Drop Logback from POM.xml 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>Copy the code
2. Configuration file
2.1 log4j2. XML
Use XML format configuration files without adding additional dependent libraries.
2.2 log4j2.yaml / log4j2.yml
Use yamL/YML configuration files. Additional dependency libraries need to be introduced
<! - analytical yml configuration - > < the 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>Copy the code
2.3 log4j2. Json
Using jSON-formatted configuration files requires the introduction of additional dependent libraries
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>Copy the code
3. Modify the Spring Boot configuration
Specify the Spring Boot configuration file
The application.yaml file is configured as follows
logging:
config: classpath:log4j2.xmlCopy the code
Log4j2 Log configuration
For details about Log4j2 configuration, visit the official documentation
An overview of the
This section describes the basic information about Log4j2
Log levels are classified into:
- I’m tracing it.
- Debug.
- Info
- Warn
- Error (error)
- Fatal
Here is a RollingFileAppender that is often used by bloggers
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>[%d] - [%c] - [%highlight{%level}] - [%method] - [%t] - %msg%n</Pattern>
</PatternLayout>
</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 * * * *? evaluateOnStartup="true"/>
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="fileLogger" level="debug" additivity="false">
<AppenderRef ref="logService"/>
<AppenderRef ref="STDOUT"/>
</Logger>
<Root level="trace">
<AppenderRef ref="STDOUT"/>
</Root>
</Loggers>
</Configuration>Copy the code
1. The Configuration parameters
status
: Level enumeration that controls the output of Log4j event information. The default value is ERRORname
: Configuration namestrict
: Whether to use a strict XML format. Recommended, standard developer configuration writing, do not support JSONP configuration- . You can refer to the official documentation for other configurations
2. Properties
Sets the global parameter variables of the configuration file. Used to reduce repeated encoding of custom configuration information.
<Properties>
<Property name="filepath">/tmp/log4j2</Property>
</Properties>Copy the code
In the following sections, ${filepath} can be used instead of/TMP /log4j2
3. Appenders
Log4j2 provides a rich Appender
- AsyncAppender Sets appender to output logs asynchronously
- CassandraAppender outputs to the Cassandra store
- ConsoleAppender output console
- FailoverAppender Sets appender error retry
- FileAppender outputs to a file
- FlumeAppender outputs to Flume
- JDBCAppender outputs to relational database tables for JDBC connections
- The JMS Appender outputs to the messaging service
- JPAAppender outputs to a relational row database using A JPA connection
- HttpAppender output to Http Service
- KafkaAppender outputs to Kafka
- MemoryMappedFileAppender outputs to memory
- NoSQLAppender outputs to the NoSQL database
- OutputStreamAppender Appender of the File/Socket type
- RandomAccessFileAppender performs 0.2 to 2 times better than FileAppder
- RollingFileAppender outputs to files that can be packaged according to rules
- RollingRandomAccessFileAppender ditto
- SMTPAppender Output in email format
- SocketAppender Sends logs in socket mode
More commonly used in projects are ConsoleAppender and RollingFileAppender.
The Appender configuration parameters described above follow
<Appenders> <! -- ConsoleAppender --> <! -- name Appender name --> <! -- target enumeration (SYSTEM_OUT, SYSTEM_ERR). Default SYSTEM_OUT --> <Console name="STDOUT" target="SYSTEM_OUT"> <! Output format - Detailed configuration see below -- -- > < PatternLayout > < Pattern > [% d] - [% c] - [% highlight {% level}] - [method] % - [% t] - % MSG % n < / Pattern > </PatternLayout> </Console> <! -- RollingFileAppender --> <! FileName Specifies the output problem name, using the absolute path to ensure that the log location is correct, and that the directory has process user write permission --> <! -- filePattern File name rule for log rollback --> <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> <! -- Roll back files by Cron scheduled task --> <! -- Schedule Cron expression --> <! EvaluateOnStartup (rule: on startup, check to determine the last modification time of the target file, if the cron rule determines that the file needs to be rolled back, then roll back the file.) --> <CronTriggeringPolicy schedule="1 * * * *? evaluateOnStartup="true"/>
</Policies>
</RollingFile>
</Appenders>Copy the code
3.2 Log output rule Layouts
Layout has multiple output formats
- CSV
- GELF
- HTML
- JSON
- Pattern
- .
In the project, Pattern is generally used to output information line by line. The configuration is as follows:
<! - excerpt configuration - > < PatternLayout > < Pattern > [% d] - [% c] - [% highlight {% level}] - [method] % - [% t] - % MSG % n < / Pattern > </PatternLayout>Copy the code
% + char/word indicates an output message or format
Time %d / %date
Format output %d, % d {DEFAULT} 2012-11-02 14:34:02, 781% d d {UNIX_MILLIS} {} UNIX 1351866842% 1351866842781% d {MM – dd yyyy – HH: MM: ss, SSS} 2012-11-02 14:34:02, 781
Class c / % % logger
Prints the name of the called class
%c{number}, controls the length of the type
Level % level
Output levels TRACE, DEBUG, INFO, WARN, ERROR, FATAL
Color format %highlight
%heighlight{xxx}
XXX has a color style and is related to Level. It is used for debugging information
Log content % M / % MSG / %message
Text styles can be added
Line % n
Depending on the output of the operating system, it is best not to use \n, \r\n and other newline symbols
There are many other symbols for reference
The official documentation
4. Loggers
- Must contain one
Root
Element, not setRoot
Element will default to a configuration similar to the following
<Root level="error">
<AppenderRef ref="Console" />
</Root>Copy the code
- Configure other developer custom
Logger
<Loggers> <! -- name mandatory and unique --> <! -- level sets the lowest level of output to default error --> <! -- Whether additivity outputs in the parent Logger, defaulttrue -->
<Logger name="fileLogger" level="debug" additivity="false"> <! Appender name defined above --> <AppenderRef ref="logService"/>
<AppenderRef ref="STDOUT"/>
</Logger>
<Root level="ERROR">
<AppenderRef ref="STDOUT"/>
</Root>
</Loggers>Copy the code
Using a Logger
In the demo, for 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/AP 11:10 a.m. */ @service public class Log4j2ServiceImpl implements Log4j2Service {// Use LogManager to obtain configuration Logger private static Logger logger = LogManager.getLogger("fileLogger"); @override public void info(String MSG) {Override public void info(String MSG) {Override public void info(String MSG) {Override public void info(String MSG) { Use '{}' instead of '+' 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"); }}Copy the code
conclusion
The previous configuration steps, configuration, and usage steps roughly describe the use of Log4j2.
Comments are welcome to point out errors or explore related issues
More exciting articles, pay attention to the public number [ToBeTopJavaer], but also the following tens of thousands of yuan boutique VIP resources for free waiting for you to take!!Copy the code