- Spring5 uses the log4j2 package to configure Maven dependencies
<dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.14.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.14.1</version> </dependency> <! -- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j-impl --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.14.1</version> <scope>test</scope> </dependency> Copy the code
- Add a log4j2 configuration file to the Resources folder called
log4j2.xml
And add the configuration information<configuration status="WARN" monitorInterval="30"> <Properties> <! ${variable name} --> <Property name="logFilePath">log</Property> <Property name="logFileName">test.log</Property> </Properties> <! Appenders: define output content, output format, output method, log saving policy, etc. Use the following tags [console,File,RollingFile]--> <appenders> <! --console: console output configuration --> <console name="Console" target="SYSTEM_OUT"> <! PatternLayout: Format of the output log. LOG4J2 defines the output code, see Part 2. <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> </console> <! --File: synchronize output log to local File --> <File name="log" fileName="${logFilePath}/${logFileName}" append="true"> <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/> </File> </appenders> <! An appender will not work until logger is defined and appender is appended. <loggers> <! -- the Root node is used to specify the Root log for the project. If Logger is not specified separately, the Root log will be used by default. <root level="info"> <appender-ref ref="Console"/> <appender-ref ref="log"/> </root> </loggers> </configuration> Copy the code
Reference:Log4j2 configuration
- call
public class AccountServiceTest { private static final Logger logger = LoggerFactory.getLogger(AccountServiceTest.class); // Get the Logger from LoggerFactory @Test public void transferTest2(a) { ApplicationContext context = new AnnotationConfigApplicationContext(TxConfig.class); AccountService accountService = context.getBean("accountService", AccountService.class); int res = accountService.transfer(1.2.new BigDecimal("100")); if (res > 0) logger.info("Transfer successful"); else logger.info("Transfer failed"); }}Copy the code
Note that import is
import org.slf4j.Logger; import org.slf4j.LoggerFactory; Copy the code