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;
}
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java操作日志记录_通用日志记录(java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 就业阶段-java语言进价_day01
- 下一篇: 数据结构之图:加权有向图与dijkstr