java 日志实现_JAVA实现通用日志记录

/*** 统一日志处理Handler

*@authorMingchenchen

**/

public classLogAopHandler {

@AutowiredprivateAuditLogDao auditLogDao;/*** controller层面记录操作日志

* 注意此处是aop:around的 因为需要得到请求前的参数以及请求后接口返回的结果

*@throwsThrowable*/

public Object doSaveLog(ProceedingJoinPoint joinPoint) throwsThrowable {

MethodSignature method=(MethodSignature) joinPoint.getSignature();

String methodName=method.getName();

Object[] objects=joinPoint.getArgs();

String requestBody= null;if (objects!=null && objects.length>0) {for(Object object : objects) {if (object == null) {

requestBody= null;//POST接口参数为空 比如删除XXX

}else if (object instanceofString) {

requestBody= (String) object;//有些接口直接把参数转换成对象了

}else{

requestBody=JSONObject.toJSONString(object);

}

}

}//只记录POST方法的日志

boolean isNeedSaveLog = false;//此处不能用getAnnotationByType 是JAVA8的特性,因为注解能够重名,所以得到的是数组

RequestMapping annotation = method.getMethod().getAnnotation(RequestMapping.class);for(RequestMethod requestMethod : annotation.method()) {if (requestMethod==RequestMethod.POST) {

isNeedSaveLog= true;

}

}

JSONObject requestBodyJson= null;try{

requestBodyJson=JSONObject.parseObject(requestBody);

}catch(Exception e) {//do nothing 即POST请求没传body

}

HttpServletRequest request=RequestContextUtil.getRequestByCurrentContext();

String userName=RequestContextUtil.getUserNameByCurrentContext();if(StringUtil.isEmpty(userName)) {try{

userName= DmsCache.get(requestBodyJson.getString("userName")).getName();

}catch(Exception e) {

userName=RequestContextUtil.getAsynUserInfoByAutoDeploy().getName();

}

}//得到request的参数后让方法执行它//注意around的情况下需要返回result 否则将不会返回值给请求者

Object result =joinPoint.proceed(objects);try{

JSONObject resultJson=JSONObject.parseObject(result.toString());if (isNeedSaveLog) {//如果是POST请求 则记录日志

LogTypeEnum logTypeEnum =LogTypeEnum.getDesByMethodName(methodName);if (logTypeEnum != null) {

AuditLogEntity auditLogEntity= newAuditLogEntity();

auditLogEntity.setUuid(StringUtil.createRandomUuid());

auditLogEntity.setOperator(userName);

auditLogEntity.setRequestIp(request.getRemoteAddr());

auditLogEntity.setRequestUrl(request.getRequestURI().replace("/cloud-master", ""));

auditLogEntity.setEventType(logTypeEnum.getKey());

auditLogEntity.setEventDesc(logTypeEnum.getDescription());

auditLogEntity.setRequest(requestBody);int isSuccess = "200".equals(resultJson.getString("code")) ? 1 : 0;

auditLogEntity.setSuccessFlag(isSuccess);

auditLogEntity.setResponse(result.toString());

auditLogEntity.setCreateTime(newDate());

auditLogDao.insert(auditLogEntity);

}

}

}catch(Exception e) {

e.printStackTrace();

}returnresult;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值