Aop自定义注解生成日志
1.编写自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OpetionLog {
String value() default "";
}
2.Controller
@PostMapping("updatestate/{id}")
@ApiOperation("更改科室启用状态")
@OpetionLog("更改科室启用状态")
public Result updateStatus(@PathVariable Integer id) throws UnknownHostException {
log.info("修改科室启用状态");
return departmentService.updateStatus(id);
}
3.切面类(控制台日志)
@Component
@Aspect
public class ParamaterLogAop {
private static Logger log = Logger.getLogger(String.valueOf(ParamaterLogAop.class));
private long start = 0;
@Pointcut("execution(* com.aaa.controller.*.*(..))")
public void haha(){}
@Before("haha()")
public void before(JoinPoint point){
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
HttpServletResponse response = requestAttributes.getResponse();
String addr = request.getRemoteAddr();
String uri = request.getRequestURI();
Object[] args = point.getArgs();
start = System.currentTimeMillis();
log.info("===================请求的地址是:================="+addr);
log.info("===================请求的路径是:================="+uri);
log.info("===================请求的参数是:================="+ Arrays.toString(args));
}
@AfterReturning("haha()")
public void after(){
long end = System.currentTimeMillis();
log.info("=================耗时================="+ (end-start));
log.info("=================结束了=================");
}
}
4.切面类(数据库日志表)
@Component
@Aspect
public class OptionsLogAop {
@Resource
private HttpSession httpSession;
@Resource
private LogsMapper logsMapper;
@AfterReturning(pointcut = "@annotation(opetionLog)", returning = "result")
public void insertLog(JoinPoint joinPoint, OpetionLog opetionLog, Result result) throws UnknownHostException {
String logTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
String addr = InetAddress.getLocalHost().getHostAddress();
String name = ((DoctorDTO)httpSession.getAttribute("doctor")).getName();
String operation = opetionLog.value();
Object[] args = joinPoint.getArgs();
String code = result.getCode().toString();
LogsDTO logsDTO = new LogsDTO(null, name, operation, logTime, addr, Arrays.toString(args), code);
logsMapper.insertLogs(logsDTO);
}
}
4.1LogsDTO
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LogsDTO implements Serializable {
private static final long serialVersionUID = -28616532886171515L;
private Integer id;
private String name;
private String operation;
private String time;
private String addr;
private String data;
private String result;
}
4.2LogsMapper
int insertLogs(LogsDTO logsDTO);
<insert id="insertLogs">
insert into logs
values (null, #{name}, #{operation},#{time},
#{addr},#{data},#{result})
</insert>
5.结果
5.1控制台
5.2数据库日志表