@Aspect @Component public class Log { private static Logger logger = LogManager.getLogger(Log.class); private String method; private String ip; private int port; private String host; private String url; /** * 定义切入点 */ @Pointcut("execution(public * com.angin.iit.controller..*.*(..))") public void log() { } /** * 执行方法前 获取client参数 * * @param joinPoint */ @Before("log()") public void doBefore(JoinPoint joinPoint) { //取到request ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); ip = request.getRemoteAddr();//客户端ip host = request.getRemoteHost();//客户端主机 method = request.getMethod();//客户端请求方法 port = request.getRemotePort();//客户端请求port url=request.getRequestURL().toString();//请求url //记录client信息 logger.info("client:ip=" + ip + ";host=" + host + ";method=" + method + ";port=" + port+";url="+url); //类名 String classname = joinPoint.getTarget().getClass().getSimpleName(); //方法名 String methodName = joinPoint.getSignature().getName(); //参数 List<Object> args = Arrays.asList(joinPoint.getArgs()); String paraJsonString = JSON.toJSONString(args, SerializerFeature.DisableCircularReferenceDetect); //日志记录 类 方法 参数 logger.info("class name: " + classname + ", method name: " + methodName + ";parameters: " + paraJsonString); } /** * 方法执行 * * @param proceedingJoinPoint * @return * @throws Throwable */ @Around("log()") public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { Object obj = proceedingJoinPoint.proceed(); logger.info("return:" + obj); return obj; } /** * 异常处理 * * @param e */ @AfterThrowing(pointcut = "log()", throwing = "e") public void doException(Throwable e) { if (e != null) { logger.error("doException系统异常:" + e.getMessage(), e); } }
之前记录日志的时候,都是在controller里 每个方法中添加,使用aop 节约了很多时间,而且维护起来更方便。