sprinngboot Aop 日志
时间: 2024-01-16 20:02:30 浏览: 37
可以使用 Spring AOP 和 Log4j2 来实现在 Spring Boot 中记录日志。
首先,在 pom.xml 中添加 Spring AOP 和 Log4j2 依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</dependency>
```
然后,在 application.properties 中配置 Log4j2:
```properties
# Log4j2
logging.level.root=info
logging.config=classpath:log4j2.xml
```
接着,创建一个切面类,在该类中编写日志记录逻辑:
```java
@Aspect
@Component
public class LoggingAspect {
private static final Logger logger = LogManager.getLogger(LoggingAspect.class);
@Before("execution(* com.example.demo.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
logger.info("Entering " + joinPoint.getSignature().getDeclaringTypeName() + " : " + joinPoint.getSignature().getName());
}
@AfterReturning(value = "execution(* com.example.demo.*.*(..))", returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
logger.info("Exiting " + joinPoint.getSignature().getDeclaringTypeName() + " : " + joinPoint.getSignature().getName() + " with result " + result);
}
}
```
上面的切面类中,@Before 注解表示在被切入的方法执行前执行,@AfterReturning 注解表示在被切入的方法执行后执行,并且只有在方法成功返回时才会执行。
最后,创建 log4j2.xml 文件,配置日志输出格式和输出位置:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<File name="File" fileName="logs/app.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>
```
上面的配置将日志输出到控制台和文件中。
至此,我们已经完成了在 Spring Boot 中使用 AOP 和 Log4j2 记录日志的配置。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)