springboot 注解打印接口调用日志
时间: 2023-05-22 10:06:44 浏览: 196
你可以使用 @Slf4j 注解和 AOP 统一处理打印日志,具体实现可参考以下代码:
1. 引入依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
```
2. 在应用主类上添加 @EnableAspectJAutoProxy 注解启用 AOP:
```java
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
3. 定义切面类:
```java
@Aspect
@Component
@Slf4j
public class LogAspect {
@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)" +
"||@annotation(org.springframework.web.bind.annotation.GetMapping)" +
"||@annotation(org.springframework.web.bind.annotation.PostMapping)" +
"||@annotation(org.springframework.web.bind.annotation.PutMapping)" +
"||@annotation(org.springframework.web.bind.annotation.DeleteMapping)")
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录请求内容
log.info("URL : " + request.getRequestURL().toString());
log.info("HTTP_METHOD : " + request.getMethod());
log.info("IP : " + request.getRemoteAddr());
// 记录调用方法
log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
// 记录请求参数
log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) {
// 记录响应内容
log.info("RESPONSE : " + ret);
}
}
```
4. 在需要打印日志的接口方法上添加 @RequestMapping 等注解即可。
压缩文件的操作请参考以下代码:
```java
public static void zip(Path sourcePath, Path zipPath) throws IOException {
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zipPath));
Stream<Path> paths = Files.walk(sourcePath)) {
paths.filter(p -> !Files.isDirectory(p))
.forEach(p -> {
ZipEntry entry = new ZipEntry(sourcePath.relativize(p).toString());
try {
zos.putNextEntry(entry);
zos.write(Files.readAllBytes(p));
zos.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
```
对于中文加密的问题,我不是很确定您要表达的意思,请再提供更详细的问题描述。
阅读全文