java日志
报警 接入钉钉
思路 目前java应用都是大多数使用logback,可以自定logback appender来对日志进行拦截,既然是报警只拦截ERROR即可,具体怎么处理是接入钉钉,还是企业微信,或者邮件根据具体需要处理即可。
@Slf4j
public class DingUtils {
public static Map 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 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);
}
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()+"×tamp=" + timestamp + "&sign=" + sign;
Map map = new HashMap<>();
map.put("msgtype","text");
Map 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条)