aop记录日志

这里用注解的形式来完成日志记录

先贴代码

@Aspect
@Component
public class LogAspect{
private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

@Pointcut("@annotation(com.crsri.common.annotation.Log)")
public void logPointCut() {
}
@Autowired
private LogService logService;

@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
    //long beginTime = System.currentTimeMillis();
    // 执行方法
    Object result = point.proceed();
    // 执行时长(毫秒)
    //long time = System.currentTimeMillis() - beginTime;
    //异步保存日志
    saveLog(point);
    return result;
}

在这里插入图片描述

这里定义一个方法呼应前面的方法将point传过来
void saveLog(ProceedingJoinPoint joinPoint) throws InterruptedException {
//创建对象
LogDO sysLog = new LogDO();
//获取被代理对象
BasicController basicController=(BasicController)joinPoint.getTarget();
//get方法获取operationinfo
String operationinfo = basicController.getOperationinfo();
sysLog.setOperationInfo(operationinfo);
//get方法获取operationtype
String operationtype = basicController.getOperationtype();
sysLog.setOperationType(operationtype);
//get方法获取projectID
String projectID = basicController.getProjectID();
sysLog.setProjectId(projectID);
// 将BasicController重置
basicController.setLogInfo(null, null, null);
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//Method method = signature.getMethod();
/* Log syslog = method.getAnnotation(Log.class); /
/

* if (syslog != null) { // 注解上的描述 sysLog.setOperationInfo(operationinfo); }
*/
// 请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setOperationFunction((className + “.” + methodName + “()”));
// 请求的参数
Object[] args = joinPoint.getArgs();
try {
String params = JSONUtils.beanToJson(args[0]).substring(0, 4999);
sysLog.setParams(params);
} catch (Exception e) {

    }
	/*
	 * String[] parameterNames = signature.getParameterNames(); for (int i = 0; i <
	 * parameterNames.length; i++) { String string = parameterNames[i];
	 * if(parameterNames[i].equals("pro")) {
	 * System.out.println("刘飞------------------"+args[i]); } }
	 */
    // 获取request
    HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
    // 设置IP地址
    sysLog.setLogIP(IPUtils.getIpAddr(request));
    sysLog.setOperationAPI(HttpContextUtils.getApiUrL(request));
    // 用户名
    User currUser = ShiroUtil.getUser();
    if (null == currUser) {
        if (null != sysLog.getParams()) {
            sysLog.setUserID("");
            sysLog.setParams(sysLog.getParams());
        } 
    } else {
        sysLog.setUserID(ShiroUtil.getUserId());
        sysLog.setUsername(ShiroUtil.getUser().getUsername());
    }
    // 系统当前时间
    Date date = new Date();
    sysLog.setOperationTime(date);
    sysLog.setOperationId(UUID.randomUUID().toString());
    logService.addLog(sysLog);//添加日志
}

在这里插入图片描述

// 请求的参数
Object[] args = joinPoint.getArgs();
try {
String params = JSONUtils.beanToJson(args[0]).substring(0, 4999);
sysLog.setParams(params);
} catch (Exception e) {

    }

/*
* String[] parameterNames = signature.getParameterNames(); for (int i = 0; i <
* parameterNames.length; i++) { String string = parameterNames[i];
* if(parameterNames[i].equals(“pro”)) {
* System.out.println(“刘飞------------------”+args[i]); } }
*/
这里是将日志中参数取出来进行一个遍历
parameterNames是参数名字
args[i]是参数的值

// 获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
// 设置IP地址
sysLog.setLogIP(IPUtils.getIpAddr(request));
sysLog.setOperationAPI(HttpContextUtils.getApiUrL(request));
// 用户名
User currUser = ShiroUtil.getUser();
if (null == currUser) {
if (null != sysLog.getParams()) {
sysLog.setUserID("");
sysLog.setParams(sysLog.getParams());
}
} else {
sysLog.setUserID(ShiroUtil.getUserId());
sysLog.setUsername(ShiroUtil.getUser().getUsername());
}
// 系统当前时间
Date date = new Date();
sysLog.setOperationTime(date);
sysLog.setOperationId(UUID.randomUUID().toString());
logService.addLog(sysLog);//添加日志
在这里插入图片描述

public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest() {
return((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
}

public static String getApiUrL(HttpServletRequest req) {
	return req.getRequestURI();
}

}

这里定义一个basicController做父类供其他类继承
public class BasicController{
//登录、注销、增加、修改、删除、查询、计算、导入、导出、上传、下载、其他、锁屏
public static final String Login = “登录”;
public static final String Logout = “注销”;
public static final String Add = “增加”;
public static final String Update = “修改”;
public static final String Delete = “删除”;
public static final String Search = “查询”;
public static final String Calculate = “计算”;
public static final String Import = “导入”;
public static final String Export = “导出”;
public static final String Upload = “上传”;
public static final String Download = “下载”;
public static final String Other = “其他”;
public static final String Lock = “锁屏”;

private String operationtype;
private String operationinfo;
private String ProjectID;

public String getOperationtype() {
	return operationtype;
}
public void setOperationtype(String operationtype) {
	this.operationtype = operationtype;
}
public String getOperationinfo() {
	return operationinfo;
}
public void setOperationinfo(String operationinfo) {
	this.operationinfo = operationinfo;
}
public String getProjectID() {
	return ProjectID;
}
public void setProjectID(String projectID) {
	ProjectID = projectID;
}
public void setLogInfo(String operationtype,String operationinfo,String ProjectID) {
	this.operationinfo = operationinfo;
	this.operationtype = operationtype;
	this.ProjectID=ProjectID;
}
@Override
public String toString() {
	return "BasicController [operationtype=" + operationtype + ", operationinfo=" + operationinfo + ", ProjectID="
			+ ProjectID + "]";
}

}

下面我们来随便用一个类下日志试试
@Controller
@RequestMapping(“user”)
public class UserController extends BasicController{
@Autowired
private UserService userService;

@Log
@RequestMapping(value="/getUser",method=RequestMethod.GET)
@ResponseBody
public ApiResponse getUser(int page,int limit ,User r){  
	List<User> user= userService.queryUserAndUserList(page, limit, r);
	int count=userService.getCountUser(r);
	setLogInfo(Search, "查询用户信息",null);
	return ApiResponse.ofSuccess(user, count);
}

在这里插入图片描述
下面是定义的@log 注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default “”;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值