开启左侧

springboot+企微完成项目异常告警

[复制链接]
在线会员 dciEM 发表于 2022-12-30 15:25:17 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题
httpServletRequest.getParameterMap()为空_凡是凡是轶崔的专客-CSDN专客
群机械人设置分析 - 交心文档 - 企业微疑开辟者中间 (qq.com)
因为名目中临时不交进日记体系,招致平常检察非常疑息十分的没有便利。并且屡屡皆需要产物,尝试发明了才明白堕落了,那作用没有太佳。
因而分离 切里 + 全部非常拦阻 等手艺完毕分离企微的及时告警。
尔是使用企微中供给的群机械人公布非常疑息,新修一个机械人会供给一个Webhook地点
springboot+企微完毕名目非常告警-1.jpg


开辟者能够按供给的Webhook倡议HTTP POST 恳求,便可完毕给该群组收收消息。具体能够参照文章:群机械人设置分析 - 交心文档 - 企业微疑开辟者中间 (qq.com)
使用的消息实质范例:markdown范例
  1. {"msgtype":"markdown","markdown":{"content": "及时新删用户反应<font color="warning">132例</font>,请相干共事留神。\n
  2.         >范例:<font color="co妹妹ent">用户反应</font>>一般用户反应:<font color="co妹妹ent">117例</font>>VIP用户反应:<font color="co妹妹ent">15例</font>"}}
复造代码
参数可否必挖分析
msgtype消息范例,此时牢固为markdown
contentmarkdown实质,最少没有超越4096个字节,必需是utf8编码
使用启事:参数较少而且实质少度撑持较少。
非常告警机械人代码:
  1. @Component@Slf4jpublicclassExceptionMsgBot{privatestaticfinalString METHOD_GET ="GET";privatestaticfinalString METHOD_POST ="POST";/**
  2.      * 企微机械人webhook地点
  3.      */@Value("${ExceptionMsgBot.url}")privateString url;/**
  4.      * 可否启动
  5.      */@Value("${ExceptionMsgBot.isEnable:true}")privateBoolean isEnable;/**
  6.      * 最年夜少度
  7.      */@Value("${ExceptionMsgBot.maxSize:2500}")privateint maxSize;publicvoidsend(Exception e,HttpServletRequest request){if(!isEnable){return;}String title ="题目";//时间String now =DateUtil.format(newDate(),DatePattern.NORM_DATETIME_FORMAT);//恳求urlString api = request.getRequestURL().toString();//恳求参数String params =JSONUtil.toJsonStr(request.getAttribute("params"));if(!StringUtils.isEmpty(params)){//将json转成一般string
  8.             params = params.replace(""","\\"");}//效劳器IPString serverIP =NetUtil.getLocalhostStr();//客户端IPString clientIP = request.getRemoteAddr();String textMsg ="{\n"+"    "msgtype": "markdown",\n"+"    "markdown": {\n"+"        "content": ""+ title +"\\n\n"+"         【url】: "+ api +" \n"+"         【参数】: "+ params +" \n"+"         【时间】: "+ now +" \n"+"         【serverIp】: "+ serverIP +" \n"+"         【clientIp】: "+ clientIP +" \n"+"         【message】: "+ e.getMessage()+" \n"+"         【cause】: "+ e.getCause()+" \n"+"         【StackTrace】: "+ e +"  "\n"+"    }\n"+"}\n";//收收消息HttpResponse response =HttpRequest.post(url).header(Header.CONTENT_TYPE,"application/json; charset=UTF-8").body(textMsg).execute();
  9.         log.info("【非常消息收收成果】 {}", response.body());}}
复造代码
此次设想的非常疑息主要展示8面
    恳求交心路子恳求参数目前时间效劳器ip客户端ipe.messagee.causee.stack
除恳求参数需要特别处置,其余参数均可以便利获得。
因为屡屡恳求交心,名目中会有个全部日记切里类挨印输出屡屡恳求的疑息。
那个全部日记切里类会正在加入controller之止截至拦阻,进而能够获得到屡屡恳求的参数。而后将参数启拆到request,通报给内部web容器使用,也即是原文章的非常告警机械人使用。
  1. @Aspect@Configuration@Slf4jpublicclassGlobalControllerLogAspect{@Pointcut("execution (* com.*..controller..*.*(..))")publicvoidcontrollers(){}@Around("controllers()")publicObjectaroundProcess(ProceedingJoinPoint joinPoint)throwsThrowable{Object[] args = joinPoint.getArgs();long startTime =System.currentTimeMillis();Object proceed =null;try{ServletRequestAttributes attributes =(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();String uid = request.getHeader(HeaderConstant.UID);List<Object> params =newArrayList<>();if(args !=null&& args.length >0){for(Object arg : args){if(arg instanceofHttpServletRequest|| arg instanceofHttpServletResponse){continue;}elseif(arg instanceofMultipartFile){continue;}else{
  2.                         params.add(arg);}}}//保留恳求参数
  3.             request.setAttribute("params",JSONUtil.toJsonStr(params));
  4.             log.info("交心办法:{},uid:{},恳求参数:{}", request.getRequestURL().toString(), uid,JSONUtil.toJsonStr(params));
  5.             proceed = joinPoint.proceed(args);
  6.             log.info("照应成果:{},耗时:{}ms",JSONUtil.toJsonStr(proceed),System.currentTimeMillis()- startTime);}finally{}return proceed;}}
复造代码
能够正在 joinPoint(跟尾面) 获得到恳求参数。
非常告警机械人正在全部非常拦阻器埋面
  1. @ControllerAdvice@Slf4jpublicclassGlobalExceptionHandler{@AutowiredprivateExceptionMsgBot bot;@ExceptionHandler(value =Exception.class)publicvoidhandle(Exception e,HttpServletRequest request,HttpServletResponse response){
  2.         log.error("交心[{}]非常, ", request.getRequestURI(), e);Co妹妹onResult<Object> result =Co妹妹onResult.failed("体系出了面小成就");//埋面
  3.         bot.send(e, request);String json =JSONUtil.toJsonStr(result);
  4.         response.setHeader("Content-Type","application/json; charset=UTF-8");try{
  5.             response.getWriter().write(json);}catch(IOException ex){
  6.             log.error("交心[{}]IO非常, ", request.getRequestURI(), ex);}}}
复造代码
当有非常疑息被全部非常拦阻器捕捉时,保留非常日记的共时,收收告警疑息报告开辟等相干职员处置。
结果:
  1. 非常告警,请相干共事留神!
  2.          【url】: http://172.18.139.x:9001/xxx
  3.          【参数】: ["uid",{"f1":9,"f2":2,"f3":2377,"f4":false,"f5":"","f6":1}]
  4.          【时间】: 2022-04-14 16:35:28
  5.          【serverIp】: 172.18.139.x
  6.          【clientIp】: 172.18.139.x
  7.          【message】: xxx不克不及为空
  8.          【cause】: null
  9.          【StackTrace】: com.xxx.co妹妹on.component.exception.ApiException: xxx不克不及为空  
复造代码
完善~
您需要登录后才可以回帖 登录 | 立即注册 qq_login

本版积分规则

发布主题
阅读排行更多+
用专业创造成效
400-778-7781
周一至周五 9:00-18:00
意见反馈:server@mailiao.group
紧急联系:181-67184787
ftqrcode

扫一扫关注我们

Powered by 职贝云数A新零售门户 X3.5© 2004-2025 职贝云数 Inc.( 蜀ICP备2024104722号 )