package com.netauth.utils.component; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface LogAnnotation { /** * <p>Title: logtype</p> * <p>Description: 日志类型 默认为"" 即为管理员操作日志,注册日志="registeruser"</p> * @return * @author lbw * @date 2022年7月8日 */ String logtype() default ""; /** * <p>Title: paramKey</p> * <p>Description: 记录日志信息 需要从参数中取值当做日志参数时 设置此参数为所需参数key</p> * @return * @author lbw * @date 2022年7月8日 */ String paramKey() default ""; }
package com.infosec.config; import java.io.IOException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Objects; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; 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.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.alibaba.fastjson.JSONObject; import com.infosec.user.compoent.UserInternationKeyConst; import com.netauth.api.logcollection.Log; import com.netauth.utils.Const; import com.netauth.utils.GetMacAddress; import com.netauth.utils.LogConst; import com.netauth.utils.component.LocaleMessageSourceService; import com.netauth.utils.component.LogAnnotation; import com.netauth.utils.currentuser.LoginUserUtil; import com.netauth.utils.gateway.GatewayConst; import com.netauth.utils.jsonresult.JsonErrotCode; import com.netauth.utils.jsonresult.JsonResult; import io.swagger.annotations.ApiOperation; @Aspect @Configuration public class LogAspect { @Resource private LocaleMessageSourceService localeMessageSourceService; @Autowired private Log log; public LogAspect() { } @Pointcut("@within(com.netauth.utils.component.LogAnnotation) || @annotation(com.netauth.utils.component.LogAnnotation)") public void pointCutMethod() { } // 声明环绕通知 @Around("pointCutMethod()") public Object doAround(ProceedingJoinPoint pjp) throws Throwable { Long startTime = System.currentTimeMillis(); // 获取request对象 RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; Object ret = null; if(sra == null) { ret = pjp.proceed(); return ret; } HttpServletRequest request = sra.getRequest(); String requestURI = request.getServletPath(); Map<String, Object> localUser = LoginUserUtil.getLoginUser(request); boolean exceptionFlag = false; Exception exportEx = null; try { ret = pjp.proceed(); } catch (Exception e) { if(requestURI != null && requestURI.indexOf("/export/") != -1) { exceptionFlag = true; exportEx = e; }else { throw e; } } Long endTime = System.currentTimeMillis(); //设置请求路径 if(StringUtils.isEmpty(requestURI) || requestURI.contains(GatewayConst.CLIENT_NO_FILTER)) { // }else { addLog(request,requestURI,exceptionFlag,localUser,pjp,endTime-startTime,ret); } if(exceptionFlag) { throw exportEx; } return ret; } //获取参数名和参数值 public Map<String, Object> getParam(ProceedingJoinPoint proceedingJoinPoint) { Map<String, Object> map = new HashMap<String, Object>(); Object[] values = proceedingJoinPoint.getArgs(); String[] names = ((MethodSignature) proceedingJoinPoint.getSignature()).getParameterNames(); for (int i = 0; i < names.length; i++) { map.put(names[i], values[i]); } return map; } private void addLog(HttpServletRequest request,String requestURI,boolean exceptionFlag,Map<String, Object> localUser,ProceedingJoinPoint pjp,Long time,Object ret) throws IOException { String apiName; String logType; MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); apiName = Objects.nonNull(apiOperation) ? apiOperation.value() : ""; LogAnnotation annotation = method.getAnnotation(LogAnnotation.class); if(annotation == null) { annotation = pjp.getTarget().getClass().getAnnotation(LogAnnotation.class); } logType = annotation.logtype(); String msg = ""; String code = ""; String model = ""; String appName = ""; String operation = ""; int logLevel = Log.LOG_LEVEL_WARN; int result = Log.RESULT_FAIULE; String[] split = requestURI.split("/"); appName = !StringUtils.isEmpty(split[1])? split[1] : appName; model = !StringUtils.isEmpty(split[2])? split[2] : model; operation = !StringUtils.isEmpty(split[3])? split[3] : operation; JsonResult res = null; if(ret!= null && ret instanceof JsonResult) { res = (JsonResult) ret ; code = res.getCode(); msg = res.getMsg(); } //没有响应 且操作类型为导出 if(ret == null && "export".equals(operation)) { //根据是否异常来设置code和msg if(exceptionFlag) { code = JsonErrotCode.FAIL_CODE; }else { code = JsonErrotCode.SUCCESS_CODE; } } String localUserLoginName = ""; String localUserName = ""; String localUserRoles = ""; String localUserDn = ""; String userClientIp = ""; //根据响应code首字母判断成功失败 if(code.startsWith("I")) { logLevel = Log.LOG_LEVEL_INFO; result = Log.RESULT_SUCCESS; if(StringUtils.isEmpty(msg)) { msg = apiName + "成功"; } } else if(code.startsWith("W")) { logLevel = Log.LOG_LEVEL_WARN; result = Log.RESULT_FAIULE; if(StringUtils.isEmpty(msg)) { msg = apiName + "失败"; } } else if(code.startsWith("E")) { logLevel = Log.LOG_LEVEL_ERROR; result = Log.RESULT_FAIULE; msg = apiName+" 异常 " + (StringUtils.isEmpty(msg) ? "" : msg); if(res != null) { res.setMsg(localeMessageSourceService.getMessage(UserInternationKeyConst.SYS_EXCEPTION)); } } switch (operation) { case "get": operation = Log.HOWS_READ; break; case "update": operation = Log.HOWS_MODIFY; break; case "del": operation = Log.HOWS_DEL; break; case "add": operation = Log.HOWS_ADD; break; case "login": operation = Log.HOWS_LOGIN; break; case "export": operation = Log.HOWS_EXPORT; break; case "import": operation = Log.HOWS_IMPORT; break; case "download": operation = Log.HOWS_DOWNLOAD; break; default: operation = Log.HOWS_OTHERS; break; } //没有登录调用接口(对外API,注册) if (localUser == null) { if( LogConst.LOGTYPE_API.equals(appName) ) { //对外API String header = request.getHeader(Const.APPID); localUserLoginName = header; localUserName = header; appName = header; model = LogConst.LOGTYPE_API; } else if(LogConst.MODEL_FLAG_PORTAL.equals(logType) ) { if(LogConst.MODEL_FLAG_USER.equals(appName)) { model = Const.MODEL_USER; } else if(LogConst.MODEL_FLAG_SMS.equals(appName)) { model = Const.MODEL_SMS; } else if(LogConst.MODEL_FLAG_APPROVAL.equals(appName)) { model = Const.MODEL_APPROVAL; } else if(LogConst.MODEL_FLAG_PORTALMANAGER.equals(appName)) { model = Const.MODEL_PORTAL; } if(requestURI.indexOf("/get/") != -1) { operation = Log.HOWS_READ; }else if (requestURI.indexOf("/update/") != -1) { operation = Log.HOWS_MODIFY; } localUserRoles = "commonuser"; //普通用户调用日志 没有登录时取参数内的登录名做日志参数 String paramKey = annotation.paramKey(); Map<String, Object> param = getParam(pjp); localUserLoginName = (String) param.get(paramKey); localUserName = localUserLoginName; localUserDn = localUserLoginName; } userClientIp = GetMacAddress.getIpAddr(request); }else { localUserLoginName = (String) localUser.get(LoginUserUtil.USER_LOGINNAME); localUserName = (String) localUser.get(LoginUserUtil.USER_USERNAME); localUserRoles = (String) localUser.get(LoginUserUtil.USER_SYSADMIN); localUserDn = (String) localUser.get(LoginUserUtil.USER_DEPTDN); userClientIp = (String) localUser.get(LoginUserUtil.USER_CLIENTIP); } JSONObject json = new JSONObject(); json.put("logLevel", logLevel); json.put("model", model); json.put("localUserLoginName", localUserLoginName); json.put("userClientIp", userClientIp); json.put("operation", operation); json.put("result", result); json.put("msg", msg); json.put("localUserName", localUserName); json.put("localUserRoles", localUserRoles); json.put("localUserDn", localUserDn); json.put("appName", appName); json.put("requestURI", requestURI); log.writeLog(this.getClass().getName(), logLevel, model, localUserLoginName, userClientIp, operation, result, msg, localUserName, localUserRoles, localUserDn, appName,requestURI);//此处就是调用后面保存日志逻辑 } }
标签:String,annotation,切面,aop,import,日志,com,operation,Log From: https://www.cnblogs.com/cuijinlong/p/16715833.html