通过AOP与方法执行时间记录实现Java操作日志,1. 定义@LogOperation注解标记需记录的方法;2. 创建LogAspect切面类,利用@Around拦截方法执行,记录请求信息、用户、IP、URI、方法类型及执行耗时;3. 在proceed前后打点计算耗时,异常时捕获错误信息;4. 通过asyncSave异步持久化日志,避免阻塞主线程;5. 结合HttpServletRequest、SecurityContext获取上下文,增强日志可追溯性;6. 在Controller方法添加注解即可无侵入式生成带执行时间的操作日志,提升系统可观测性与审计能力。

在Java项目中,记录用户操作日志是系统审计、问题追踪和安全监控的重要手段。通过结合AOP(面向切面编程)与方法执行时间记录,可以实现无侵入式的操作日志收集,既提升代码可维护性,又增强系统的可观测性。
1. 使用AOP捕获用户操作
AOP能够在不修改业务逻辑的前提下,拦截指定方法的调用,非常适合用于日志记录。
定义一个自定义注解,标记需要记录日志的方法:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogOperation {
String value() default ""; // 操作描述
String type(); // 操作类型,如“查询”、“删除”
}
创建切面类,使用@Aspect和@Component注入Spring容器:
立即学习“Java免费学习笔记(深入)”;
@Aspect
@Component
public class LogAspect {
@Autowired
private HttpServletRequest request;
@Autowired
private OperationLogService logService; // 保存日志的服务
@Around("@annotation(logOperation)")
public Object around(ProceedingJoinPoint joinPoint, LogOperation logOperation) throws Throwable {
long startTime = System.currentTimeMillis();
// 获取请求信息
String ip = getRemoteIp();
String uri = request.getRequestURI();
String method = request.getMethod();
String username = getCurrentUsername(); // 可从SecurityContext或Token解析
Object result;
try {
result = joinPoint.proceed();
saveLog(joinPoint, logOperation, username, ip, uri, method, startTime, "SUCCESS", null);
return result;
} catch (Exception e) {
saveLog(joinPoint, logOperation, username, ip, uri, method, startTime, "FAILED", e.getMessage());
throw e;
}
}
private void saveLog(ProceedingJoinPoint joinPoint, LogOperation logOp, String user,
String ip, String uri, String method, long startTime, String status, String errorMsg) {
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
OperationLog log = new OperationLog();
log.setUsername(user);
log.setIp(ip);
log.setUri(uri);
log.setHttpMethod(method);
log.setOperationType(logOp.type());
log.setDescription(logOp.value());
log.setExecutionTime(elapsedTime);
log.setStatus(status);
log.setErrorMsg(errorMsg);
// 可异步保存,避免影响主流程
logService.asyncSave(log);
}
private String getRemoteIp() {
String ip = request.getHeader("X-Real-IP");
if (ip == null || ip.isEmpty()) {
ip = request.getRemoteAddr();
}
return ip;
}
private String getCurrentUsername() {
// 示例:从Spring Security获取
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return principal instanceof UserDetails ? ((UserDetails) principal).getUsername() : "unknown";
}}
2. 记录方法执行时间
在上述around方法中,通过System.currentTimeMillis()记录开始与结束时间,计算耗时并存入日志,便于后续分析性能瓶颈。
关键点:
- 在proceed前后分别打点,确保包含整个方法执行周期
- 即使方法抛出异常,也能记录执行时长和失败原因
- 将耗时写入日志字段executionTime,可用于监控慢操作
3. 日志内容优化与异步持久化
为避免阻塞主线程,日志保存建议采用异步方式:
@Service
public class OperationLogService {
@Async
@Transactional
public void asyncSave(OperationLog log) {
// 插入数据库
operationLogMapper.insert(log);
}}
同时可在日志中加入更多上下文信息:
- 请求参数:joinPoint.getArgs()
- 目标类与方法名:joinPoint.getSignature()
- 用户代理(User-Agent):request.getHeader("User-Agent")
4. 实际使用示例
在控制器方法上添加注解即可启用日志记录:
@RestController
public class UserController {
@LogOperation(value = "删除用户", type = "DELETE")
@DeleteMapping("/users/{id}")
public Result deleteUser(@PathVariable Long id) {
userService.delete(id);
return Result.success();
}
@LogOperation(value = "导出用户列表", type = "EXPORT")
@GetMapping("/users/export")
public void exportUsers(HttpServletResponse response) {
userService.export(response);
}}
只要方法被调用,无论成功或失败,都会生成一条带执行时间的操作日志。
基本上就这些。AOP加时间记录的方式简洁高效,适合大多数Java Web项目。关键是设计好日志模型和异步机制,保证不影响核心业务性能。










