This series is based on spring5, the latest release.
The entire code of spring5 is based on java8, with many optimizations of its own, such as the removal of many deprecated classes and methods from the code base.
In addition, the spring5 framework comes with a generic logging wrapper, but we can still integrate it with other logging frameworks, such as Log4j. However, in spring5, Log4jConfigListener is removed and Log4j2 is used.
First, introduce dependencies
Import relevant JAR packages.
Create the Log4j2 configuration file
The file name is fixed log4j2.xml.
<? The XML version = "1.0" encoding = "utf-8"? > <! -- Log levels and priorities: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL --> <! --Configuration status="INFO"> < Configuration status="INFO"> <! Define all appenders first --> <appenders> <! <console name=" console "target="SYSTEM_OUT"> <! PatternLayout pattern="%d{YYYY-MM-DD HH: MM :ss.SSS} [%t] %-5level % Logger {36} - % MSG %n"/> </console> </appenders> <! Then define logger. The appender will only work if logger is defined and an appender is introduced. - the root: Specifies the root log for the project. If Logger is not specified separately, --> <loggers> <root level="info"> <appender-ref ref="Console"/> </root> </loggers> </configuration>Copy the code
Now you can use it directly. Execute the previous test code:
The 2021-08-08 09:09:21. [the main] INFO 935 com. Alibaba. Druid. Pool. DruidDataSource -} {the dataSource - 1 inited Process finished with exit code 0Copy the code
As you can see on the console, the log information is output according to the format configured above.
Three, manually carry out separate output
We can also manually output some of our specified content log.
package com.pingguo.spring5.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UserLog { private static final Logger log = LoggerFactory.getLogger(UserLog.class); Public static void main(String[] args) {log.warn(" warning"); Log. error(" output error manually "); }}Copy the code
Execute:
The 2021-08-08 09:18:02. [the main] WARN 285 com. Pingguo. Spring5. Test. The UserLog - manual output warning 09:18:02 2021-08-08. 288 ERROR [main] Com. Pingguo. Spring5. Test. UserLog - manual output error Process finished with exit code 0Copy the code