分享spring boot controller统一日志代码
Posted NullToValue
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了分享spring boot controller统一日志代码相关的知识,希望对你有一定的参考价值。
最近项目需要做一个controller层的aop,主要解决下面问题:
1.controller日志统一打印输出json格式,兼容json和velocity 。
2.项目异常处理
3.异常邮件发送
4.页面访问统计
主要思路使用aop实现,controller参数统一使用@RequestParam接收。
controller
@RequestMapping(name = "添加个人信息", value ="/addInfo", method = RequestMethod.POST) public String addInfo(@RequestParam("idFront") MultipartFile idFront, @RequestParam("idReverse") MultipartFile idReverse, @RequestParam("idNo") String idNo, @RequestParam("realName") String realName, @RequestParam("token") String token, HttpServletRequest request) throws Exception {
aop
@Aspect @Component public class CotrollerLogAop { private final static Logger logger = LoggerFactory.getLogger(CotrollerLogAop.class); //请求信息缓存 private final static Map<String, Object[]> MethodInfo=new ConcurrentHashMap<String, Object []>(); //项目名 @Value("${base.project.name}") private String projectName; //spring boot 错误页面uri @Value("${server.error.path:/error}") private String errorPath; //邮件发送 @Autowired private EmailClient emailClient; //页面统计 @Autowired private PageStatService pageStatService; //切面 @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)") public void requestMapping() { } //增强 @Around("requestMapping()") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { long startTime=System.currentTimeMillis(); long endTime=0; Object[] objects = pjp.getArgs(); String userName = ""; String reqArray = ""; String respView = null; String respData = null; String operation = null; Object object = null; String ip = null; Boolean returnJson=false; String[] paramNames=null; String referer=null; String userAgent=null; boolean errorReq=false; try { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); operation=request.getRequestURI(); referer=request.getHeader("Referer"); if(referer==null) referer=""; userAgent=request.getHeader("User-Agent"); if(userAgent==null) userAgent=""; Method method = ((MethodSignature) pjp.getSignature()).getMethod(); if (operation.equals(errorPath)) { errorReq=true; returnJson=method.getAnnotation(ResponseBody.class)!=null; }else{ Object [] info=getMethodInfo(operation, method); returnJson=(Boolean) info[0]; paramNames=(String [])info[1]; } //请求相关参数 ip = RequestParamUtil.getClientIpAddr(request); SessionUser securityUser = (SessionUser) request.getSession().getAttribute(Constants.SESSIONKEY); if (securityUser != null) { userName = securityUser.getShowName(); } reqArray = ArrayToJsonString(objects, paramNames); //执行该方法 object = pjp.proceed(); //响应相关参数 if (returnJson) { if(object instanceof String){ respData=(String)object; }else{ respData = JSON.toJSONString(object); } } else { if (object instanceof ModelAndView) { respView = ((ModelAndView) object).getViewName(); } else { respView = (String) object; } respData = RequestParamUtil.getResponseStr(request); } //spring boot 系统错误 if(errorReq){ pageStatService.addStat("/error"); HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); if(returnJson){ Map<String, Object> map = new HashMap<String, Object>(); ResponseEntity entity = null; if (response.getStatus() == 404) { map.put("code", MsgCode.ERROR); map.put("msg", "资源不存在!"); entity = new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK); } else { map.put("code", MsgCode.ERROR); map.put("msg", "系统异常!"); entity = new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK); } emailClient.sendSysErrorEmail(operation, response.getStatus() + "-->"+respData); logger.info("<|>error_redirect<|>{}<|>{}<|>{}<|>{}<|>异常信息<|>{}<|>改写<|>{}<|>", projectName, userName, ip, operation, respData, JSON.toJSONString(map)); return entity; }else{ ModelAndView view = null; if (response.getStatus() == 404) { view = new ModelAndView("error/404"); } else { view = new ModelAndView("error/500"); } String msg=JSON.toJSONString(((ModelAndView) object).getModel()); emailClient.sendSysErrorEmail(operation, response.getStatus() + "-->"+msg); logger.info("<|>error_redirect<|>{}<|>{}<|>{}<|>{}<|>异常信息<|>{}<|>改写<|>{}<|>", projectName, userName, ip, operation, msg, view.getViewName()); return view; } } endTime=System.currentTimeMillis(); logger.info("<|>common<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>", projectName, userName, ip, operation, referer, reqArray, userAgent, respView, respData, endTime-startTime); pageStatService.addStat(operation); return object; } catch (Exception e) { endTime=System.currentTimeMillis(); if (returnJson) { BaseResp baseResp = new BaseResp(); if (e instanceof OpenException) { OpenException openException = (OpenException) e; baseResp.setFailedMsg(openException.getMessage()); logger.info("<|>common<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>", projectName, userName, ip, operation, referer, reqArray, userAgent, "", JSON.toJSONString(baseResp), endTime-startTime); } else { e.printStackTrace(); logger.info("<|>error<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>", projectName, userName, ip, operation,referer, reqArray,userAgent, e.getMessage(), startTime-endTime); baseResp.setFailedMsg("系统异常!"); emailClient.sendSysErrorEmail(operation, e.getMessage()); } return baseResp; } else { e.printStackTrace(); emailClient.sendSysErrorEmail(operation, e.getMessage()); logger.info("<|>error<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>{}<|>", projectName, userName, ip, operation, referer, reqArray, userAgent, e.getMessage(), startTime-endTime); return "error/500"; } } } //拼接请求json private String ArrayToJsonString(Object[] objects, String [] paramNames) throws Exception { StringBuilder reqArray = new StringBuilder("{"); if (paramNames!=null && paramNames.length>0 && objects != null && objects.length > 0) { for (int i = 0; i < objects.length; i++) { if (objects[i] == null) { continue; } if(paramNames.length>i) { String className = objects[i].getClass().getName(); if (className.contains("MultipartFile")) { MultipartFile multipartFile = (MultipartFile) objects[i]; reqArray.append(""").append(paramNames[i]).append("":""). append(multipartFile.getOriginalFilename()).append("","); } else { reqArray.append(""").append(paramNames[i]).append("":"). append(JSON.toJSONString(objects[i])).append(","); } }else{ break; } } } if (reqArray.length() > 1) { reqArray.replace(reqArray.length() - 1, reqArray.length(), "}"); } else { reqArray.append("}"); } return reqArray.toString(); } private Object[] getMethodInfo(String operation, Method method) throws Exception{ Object [] info=MethodInfo.get(operation); if(info==null){ info=new Object[2]; }else{ return info; } Boolean returnJson=false; if(method.getAnnotation(ResponseBody.class)!=null){ returnJson=true; } info[0]=returnJson; Annotation[][] parameterAnnotations = method.getParameterAnnotations(); List<String> list=new ArrayList<String>(); if (parameterAnnotations != null) { int i = 0; //数组增强for和普通遍历等价 for (Annotation[] parameterAnnotation : parameterAnnotations) { for (Annotation annotation : parameterAnnotation) { if (annotation instanceof RequestParam) { RequestParam param = (RequestParam) annotation; list.add(param.value()); break; } } } } info[1]=list.toArray(new String[0]); MethodInfo.put(operation, info); return info; } }
以上是关于分享spring boot controller统一日志代码的主要内容,如果未能解决你的问题,请参考以下文章
[Spring Boot ] Creating the Spring Boot Project : Demo: Creating a REST Controller