博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
分享spring boot controller统一日志代码
阅读量:5161 次
发布时间:2019-06-13

本文共 8355 字,大约阅读时间需要 27 分钟。

最近项目需要做一个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@Componentpublic class CotrollerLogAop {    private final static Logger logger = LoggerFactory.getLogger(CotrollerLogAop.class);   //请求信息缓存    private final static Map
MethodInfo=new ConcurrentHashMap
(); //项目名 @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
map = new HashMap
(); ResponseEntity entity = null; if (response.getStatus() == 404) { map.put("code", MsgCode.ERROR); map.put("msg", "资源不存在!"); entity = new ResponseEntity
>(map, HttpStatus.OK); } else { map.put("code", MsgCode.ERROR); map.put("msg", "系统异常!"); entity = new ResponseEntity
>(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
list=new ArrayList
(); 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; }}

 

posted on
2018-11-28 22:58 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/nullAndValue/p/10035617.html

你可能感兴趣的文章
windows下的C++ socket服务器(4)
查看>>
css3 2d转换3d转换以及动画的知识点汇总
查看>>
【Java】使用Eclipse进行远程调试,Linux下开启远程调试
查看>>
对Vue为什么不支持IE8的解释之一
查看>>
计算机改名导致数据库链接的诡异问题
查看>>
Java8内存模型—永久代(PermGen)和元空间(Metaspace)(转)
查看>>
ObjectiveC基础教程(第2版)
查看>>
centos 引导盘
查看>>
Notes of Daily Scrum Meeting(12.8)
查看>>
Apriori算法
查看>>
onlevelwasloaded的调用时机
查看>>
求出斐波那契数组
查看>>
lr_start_transaction/lr_end_transaction事物组合
查看>>
CodeIgniter学习笔记(四)——CI超级对象中的load装载器
查看>>
.NET CLR基本术语
查看>>
ubuntu的home目录下,Desktop等目录消失不见
查看>>
建立,查询二叉树 hdu 5444
查看>>
[Spring框架]Spring 事务管理基础入门总结.
查看>>
2017.3.24上午
查看>>
Python-常用模块及简单的案列
查看>>