码迷,mamicode.com
首页 > 编程语言 > 详细

springboot 如何使用自定义注解+aop实现全局日志持久化操作

时间:2021-02-24 13:08:30      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:lan   ons   ali   weight   type   mapper   author   document   ram   

 

1.自定一个注解

package com.hc.manager.common.aop.annotation;

import java.lang.annotation.*;

/**
* LogAnnotation
*
* @author summer.chou
* @version V1.0
* @date 2020318
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {
/**
* 模块
*/
String title() default "";

/**
* 功能
*/
String action() default "";
}



2.aop 拦截


package com.hc.manager.common.aop.aspect;

import com.alibaba.fastjson.JSON;
import com.hc.manager.common.aop.annotation.LogAnnotation;
import com.hc.manager.common.utils.HttpContextUtils;
import com.hc.manager.common.utils.IPUtils;
import com.hc.manager.entity.SysLog;
import com.hc.manager.mapper.SysLogMapper;
import com.hc.manager.service.HttpSessionService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
* 日志切面
*
* @author summer.chou
* @version V1.0
* @date 2020318
*/
@Aspect
@Component
@Slf4j
public class SysLogAspect {
@Lazy
@Resource
private SysLogMapper sysLogMapper;

@Lazy
@Resource
private HttpSessionService httpSessionService;

/**
* 此处的切点是注解的方式
* 只要出现 @LogAnnotation注解都会进入
*/
@Pointcut("@annotation(com.hc.manager.common.aop.annotation.LogAnnotation)")
public void logPointCut() {

}

/**
* 环绕增强,相当于MethodInterceptor
*/
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//执行方法
Object result = point.proceed();
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;

//保存日志
try {
saveSysLog(point, time);
} catch (Exception e) {
log.error("sysLog,exception:{}", e, e);
}

return result;
}

/**
* 把日志保存
*/
private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();

SysLog sysLog = new SysLog();
LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
if (logAnnotation != null) {
//注解上的描述
sysLog.setOperation(logAnnotation.title() + "-" + logAnnotation.action());
}

//请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setMethod(className + "." + methodName + "()");
log.info("请求{}.{}耗时{}毫秒", className, methodName, time);
try {
//请求的参数
Object[] args = joinPoint.getArgs();
String params = null;
if (args.length != 0) {
params = JSON.toJSONString(args);
}

sysLog.setParams(params);
} catch (Exception e) {
log.error("sysLog,exception:{}", e, e);
}
//获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//设置IP地址
sysLog.setIp(IPUtils.getIpAddr(request));
log.info("Ip{},接口地址{},请求方式{},入参:{}", sysLog.getIp(), request.getRequestURL(), request.getMethod(), sysLog.getParams());
//用户名
String userId = httpSessionService.getCurrentUserId();
String username = httpSessionService.getCurrentUsername();
sysLog.setUsername(username);
sysLog.setUserId(userId);
sysLog.setTime((int) time);
log.info(sysLog.toString());
sysLogMapper.insert(sysLog);

}
}

3.使用方式

使用的时候,只需要在接口上贴上 @LogAnnotation

@PostMapping("/role/permission")
@ApiOperation(value = "修改或者新增角色菜单权限接口")
@LogAnnotation(title = "角色和菜单关联接口", action = "修改或者新增角色菜单权限")
@RequiresPermissions(value = {"sys:role:update", "sys:role:add"}, logical = Logical.OR)
public DataResult operationRolePermission(@RequestBody @Valid RolePermissionOperationReqVO vo) {
rolePermissionService.addRolePermission(vo);
return DataResult.success();
}



4.效果

技术图片


 


springboot 如何使用自定义注解+aop实现全局日志持久化操作

标签:lan   ons   ali   weight   type   mapper   author   document   ram   

原文地址:https://www.cnblogs.com/summer-chou/p/14437364.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!