根据slf4j日志级别,发送钉钉预警

该博客介绍了如何实现一个基于Java的钉钉错误日志自动推送工具类,当应用程序出现ERROR级别日志时,工具会将错误信息发送到指定的钉钉机器人。同时,展示了对应的logback.xml配置文件,说明了如何设置日志记录和过滤,确保只有ERROR级别的日志被推送到钉钉。此外,还提供了一个简单的测试用例来验证配置的有效性。
摘要由CSDN通过智能技术生成

一、发送钉钉工具类

public class WarnPushUtil extends UnsynchronizedAppenderBase<ILoggingEvent> {

    private static String url = "钉钉机器人地址";

    @Override
    protected void append(ILoggingEvent event) {
        try {
            if (event.getLevel() == Level.ERROR) {

                IThrowableProxy iThrowableProxy = event.getThrowableProxy();
                StringBuilder sb = new StringBuilder();
                if (iThrowableProxy != null && iThrowableProxy instanceof ThrowableProxy) {
                    ThrowableProxy throwableProxy = (ThrowableProxy) iThrowableProxy;
                    Throwable throwable = throwableProxy.getThrowable();
                    String throwableMsg = throwable.getMessage();
                    StackTraceElementProxy[] stackTraceElementProxy = iThrowableProxy.getStackTraceElementProxyArray();
                    sb.append(event.getMessage()).append("\n");
                    if (!StringUtils.isEmpty(throwableMsg)) {
                        sb.append(throwableMsg).append("\n");
                    }
                    int i = 0;
                    for (StackTraceElementProxy proxy : stackTraceElementProxy) {
                        //只打印40行的堆栈
                        if (i < 10) {
                            sb.append(proxy.getSTEAsString()).append("\n");
                        } else {
                            break;
                        }
                        i++;
                    }
                } else {
                    sb.append(event.getMessage());
                }
                String msg = sb.toString();
                if (!StringUtils.isEmpty(msg)) {
                    sendExceptionInfo(msg);
                }
            }
        } catch (Exception e) {
            System.out.println("防止死循环");
        }
    }


    public void sendExceptionInfo(String msg) {
        try {
            Map ddMesMap = new HashMap();
            Map contentMap = new HashMap();
            contentMap.put("content", url +"knowledge异常明细:"+ msg);
            ddMesMap.put("msgtype", "text");
            ddMesMap.put("text", contentMap);
            //技术群
            post(url, JSON.toJSONString(ddMesMap));

        } catch (Exception e) {
            System.out.println("防止死循环");

        }

    }

    /**
     * 调用 API
     *
     * @param url
     * @param body
     * @return
     */
    public static String post(String url, String body) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        try {

            // 建立一个NameValuePair数组,用于存储欲传送的参数
            httpPost.addHeader("Content-type",
                    "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(body, Charset.forName("UTF-8")));

            HttpResponse response = httpClient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();

            System.out.println("statusCode:" + statusCode);
            if (statusCode != 200) {
                System.out.println("Method failed:" + response.getStatusLine());
            }

            // Read the response body
            body = EntityUtils.toString(response.getEntity());

        } catch (IOException e) {
            // 网络错误
        } finally {
            httpClient.getConnectionManager().shutdown();
            ((DefaultHttpClient) httpClient).close();
        }
        return body;
    }

}

二、配置logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- 日志最大的历史 30天 -->
    <property name="maxHistory" value="30"/>
    <property name="log_dir" value="/apache-tomcat-8.5.16" />
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <charset>UTF-8</charset>
            <pattern>%date - %level [%logger:%line] - %msg%n%ex{5}</pattern>
        </encoder>
    </appender>

    <appender name="DINGDING" class="com.xxx.WarnPushUtil">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <logger name="io.grpc" level="info" additivity="false">
        <appender-ref ref="STDOUT"/>
    </logger>

    <root level="info">
        <appender-ref ref="DINGDING"/>
    </root>

</configuration>

三、测试

@Controller
@RequestMapping("/beat")
public class BeatController {

    private Logger logger = LoggerFactory.getLogger(BeatController.class);

    @ResponseBody
    @RequestMapping("")
    public ResultBean check(){
        System.out.println("living...........");
        logger.error("出错了!");
        return ResultBean.getSuccessBean().setCode("200");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值