java日志报警接入钉钉

该博客介绍了一种使用Logback自定义Appender实现日志拦截,并结合钉钉进行错误级别报警的方法。通过读取配置文件,动态设置报警机器人,并利用HmacSHA256算法进行消息签名验证,确保消息安全发送到钉钉群。
摘要由CSDN通过智能技术生成

思路 目前java应用都是大多数使用logback,可以自定logback appender来对日志进行拦截,既然是报警只拦截ERROR即可,具体怎么处理是接入钉钉,还是企业微信,或者邮件根据具体需要处理即可。
在这里插入图片描述

@Slf4j
public class DingUtils {

    public static Map<Integer, KV> map = new HashMap<>();

    public static RateLimiter rateLimiter = null;

    public static AtomicInteger atomicInteger = new AtomicInteger(0);

    @Data
    public static class KV{
        private String k;
        private String v;
    }

    /**
     * 加载类的时候初始化
     * */
    static {
        try {
            ClassPathResource classPathResource = new ClassPathResource("prop/dingding.properties");
            InputStream in = classPathResource.getInputStream();
//            File file = new File(url.getPath(), "/prop/dingding.properties");
//            FileInputStream in = new FileInputStream(file);
            Properties properties = new Properties();
            properties.load(in);
            Enumeration<Object> keys = properties.keys();
            int count = 0;
            while (keys.hasMoreElements()){
                String k = keys.nextElement().toString();
                KV kv = new KV();
                String value = properties.getProperty(k);
                String[] split = value.split("&");
                kv.setK(split[0]);
                kv.setV(split[1]);
                map.put(count++,kv);
            }

            BigDecimal a = new BigDecimal(map.size() * 20);
            BigDecimal v = a.divide(new BigDecimal(60),2,BigDecimal.ROUND_DOWN);
            rateLimiter =  RateLimiter.create(v.doubleValue());

            System.err.println(rateLimiter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取对应机器人
     * */
    public static KV getKV(){
        //轮询每个机器人即可 (最简单了)
        int idx = atomicInteger.getAndIncrement() % map.size();
        return map.get(idx);
    }

    /**
     * 给钉钉群发送消息方法
     *
     * @param content 消息内容
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     */
    public static String sendMsg(String content) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        try {
            rateLimiter.acquire();
            content = "监控报警 ====>" + content;
            //群机器人复制到的秘钥secret
            KV kv = getKV();
            String secret = kv.getV();
            //获取系统时间戳
            long timestamp = Instant.now().toEpochMilli();
            //拼接
            String stringToSign = timestamp + "\n" + secret;
            //使用HmacSHA256算法计算签名
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            //进行Base64 encode 得到最后的sign,可以拼接进url里
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            //钉钉机器人地址(配置机器人的webhook)
            String dingUrl = kv.getK()+"&timestamp=" + timestamp + "&sign=" + sign;
            Map<String,String> map = new HashMap<>();
            map.put("msgtype","text");
            Map<String,String> body = new HashMap<>();
            body.put("content",content);
            map.put("text",JSON.toJSONString(body));
            String result = HttpUtils.post(dingUrl, map, null);
            return result;
        } catch (Exception e) {
             log.info("钉钉推送消息出现异常 ", e);
            return null;
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值