background
Use dingding’s custom robot to send abnormal information in the project to Dingding business group
The target
Alarm effect drawing
@Renderings of designated handlers
start
First of all please read the nail development documentation, any official documentation is the best article information
There are only two steps to access the nailing robot
Get the custom robotWebhook
-
Click on the group you want to send alarms to -> Group Settings -> Smart Group Assistant -> Add Robot
-
Set information about a custom robot
Robot name
Call it anything you want based on your business
Add to a Group
Group that receives alarm information
Security Settings
- User-defined keyword: A maximum of 10 keywords can be configured. A message can be sent only when at least one keyword is included in the message
- The signature of the:
- IP address: After the configuration, only the requests from the IP address range are processed. Two Settings are supported: IP address and IP address segment. The format of IPv6 address whitelist is as follows.
-
Get Webhook
Write code to send alarm information
In fact, the above said a lot of nonsense, take a look at the official documentation of the nail on the line, starting to introduce the alarm code based on JAVA
-
Send the alarm
/** * send alarm **@paramMsgType MSG type *@paramThrowable exception *@paramWhether isAt requires @ person *@paramIsAtAll whether @all *@paramatusers@Mobile phone number of the user list */ public static void alarm(MsgType msgType, Throwable throwable, boolean isAt, boolean isAtAll, List<String> atUsers) { DingConfig config = dingRobotUtil.dingConfig; if(! config.isEnable()) {return; } log.info("Nail robot - Send alarm message"); DingTalkClient client = new DefaultDingTalkClient(config.getWebhook()); OapiRobotSendRequest request = new OapiRobotSendRequest(); request.setMsgtype(msgType.getValue()); OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text(); // The content must contain "error" and other keywords, otherwise the send will fail, the keywords can be modified in the nail robot management text.setContent(buildErrMsg(throwable)); request.setText(text); if (isAt) { OapiRobotSendRequest.At at = new OapiRobotSendRequest.At(); if (CollectionUtils.isEmpty(atUsers)) { at.setAtMobiles(atUsers); } else { at.setAtMobiles(config.getAtMobiles()); } // Whether to @all at.setIsAtAll(isAtAll); The setAtMobiles parameter is not used to specify the user to @ // at.setAtUserIds(Arrays.asList("109929","32099")); request.setAt(at); } try { log.info("Nail robot - Alarm content: {}", JSON.toJSON(request)); OapiRobotSendResponse response = client.execute(request); log.info("Nail robot - Alarm end: {}", JSON.toJSON(response)); } catch (Exception e) { log.error("Nail robot - alarm failure: {}", e); }}Copy the code
-
Building message content
- The following is my personal summary of some contents that I hope to directly include in the alarm information, such as time, alarm server, log path, abnormal information and so on. You can add the information you want to see freely according to the project situation
@SneakyThrows private static String buildErrMsg(Throwable throwable) { StringBuffer msg = new StringBuffer(); InetAddress inetAddress = InetAddress.getLocalHost(); MSG. Append (" date of an error: "), append (LocalDateTime. Now (). The format (DateTimeFormatter. OfPattern (" MM - dd yyyy - HH: MM: ss "))); Localhost ("\n host name: ").append(inetaddress.gethostName ()); localhost ("\n host name: ").append(inetaddress.gethostName ()) MSG. Append (" \ n host IP: "), append (inetAddress. GetHostAddress ()), append (" \ n "); MSG. Append (" \ n log path: "), append (getLogPath ()), append (" \ n "); Msg.append ("\n").appEnd (throwable.getStackTrace()[0]).append("\n"); If (throwable instanceof ServiceException) {ServiceException e = (ServiceException) throwable; if (throwable instanceof ServiceException) {ServiceException e = (ServiceException) throwable; MSG. Append (" \ n exception information: "), append (um participant etMsg ()), append (" \ n "); } if (throwable instanceof Exception) msg.append("\n Exception message: ").append(throwable).append("\n"); return msg.toString(); } /** * Obtaining the log path ** @return {@link String} * @throws IOException IOException */ public static String getLogPath() throws IOException { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); ch.qos.logback.classic.Logger logger = context.getLogger("ROOT"); FileAppender FileAppender = (FileAppender) logger.getappender ("infoLog"); File file = new File(fileAppender.getFile()); return file.getCanonicalPath(); }Copy the code
-
Trigger point
My project uses @RestControllerAdvice to catch global exceptions, so I call alarm() directly from the exception handler I need to alert, which you can do automatically or manually, depending on your business needs
@ExceptionHandler(ServiceException.class) public ResultBody resolveBusinessException(ServiceException e) { log.info(Internal system error:, e); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); ResultBody result = ResultBody.fail(e.getCode(), e.getMsg()); request.setAttribute(RESPONSE_DATA, result); DingRobotUtil.alarm(DingRobotUtil.MsgType.TEXT, e,true.false.null); return result; } Copy the code
2021-6-8 Tuesday in Shenzhen