- 开启切面编程
<aop:aspectj-autoproxy/>
- 编写日志注解类
package com.ff.annotation;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MyLog {
public String description() default "";
}
- 切面类
package com.ff.annotation;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect
@Component
@Slf4j
public class MyLogAspect {
@Pointcut(value = "@annotation(com.ff.annotation.MyLog)")
private void pointcut() {
}
@Around(value = "pointcut() && @annotation(myLog)")
public Object around(ProceedingJoinPoint point, MyLog myLog) {
JSONObject jo = new JSONObject();
jo.put("description",myLog.description());
jo.put("clazz",point.getTarget().getClass());
jo.put("method",((MethodSignature) point.getSignature()).getMethod().getName());
jo.put("param",point.getArgs());
log.info("around-{}",jo);
try {
return point.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
return throwable.getMessage();
}
}
@AfterReturning(value = "pointcut() && @annotation(myLog)", returning = "result")
public Object afterReturning(JoinPoint joinPoint, MyLog myLog, Object result) {
log.info("afterReturning-{}",result);
return result;
}
@AfterThrowing(value = "pointcut() && @annotation(myLog)", throwing = "ex")
public void afterThrowing(JoinPoint joinPoint, MyLog myLog, Exception ex) {
log.info("请求:" + myLog.description() + " 出现异常");
}
}
- 日志记录
package com.ff.core.user.controller;
import com.ff.annotation.MyLog;
import com.ff.kafka.MessageProducer;
import com.ff.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
@Scope("prototype")
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private DemoService demoService;
@Autowired
private MessageProducer messageProducer;
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
@MyLog(description = "index请求")
public String testDubbo(@Param("j") String j){
System.out.println("城市");
return "1str";
}
}