1.定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD) // 指定该注解只能应用于方法上
@Retention(RetentionPolicy.RUNTIME) // 运行时生效
public @interface Loggable { }
2.编写切面的实现
import com.alibaba.fastjson.JSON;
import com.jeecg.modules.jmreport.domain.SignUpInfo;
import com.jeecg.modules.jmreport.mapper.WangXiaoMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@Component
@Aspect
public class RequestResponseLoggerAspect {
// private final Logger logger = LoggerFactory.getLogger(RequestResponseLoggerAspect.class);
@Autowired
private HttpServletRequest request;
@Autowired
private WangXiaoMapper wangXiaoMapper;
@Around("@annotation(loggable)")
public Object logMethodExecutionTime(ProceedingJoinPoint joinPoint, Loggable loggable) throws Throwable {
long startTime = System.currentTimeMillis();
String methodName = null;
String className = null;
Object result = null;
Map<String, String[]> parameterMap = null;
try {
parameterMap = request.getParameterMap();
methodName = joinPoint.getSignature().getName();
className = joinPoint.getTarget().getClass().getSimpleName();
result = joinPoint.proceed();
//请求正常结束的日志
saveToDatabase(methodName, className, parameterMap, result);
return result;
} catch (Exception e){
//请求出错结束的日志
saveToDatabase(methodName, className, parameterMap,e.getMessage());
return e.getMessage();
} finally {
// long endTime = System.currentTimeMillis();
// long executionTime = endTime - startTime;
// logger.info("{}#{} executed in {} ms", className, methodName, executionTime);
}
}
private void saveToDatabase(String methodName, String className, Map<String, String[]> parameterMap, Object result) {
// 保存日志到数据库(写自己的业务代码,需要如何保存日志)
}
}
3.Application启动类上添加@EnableAspectJAutoProxy注解
4.需要保存日志的controller方法上添加注解@Loggable