日志抛到 钉钉 机器人上

参考文档

  1. https://ding-doc.dingtalk.com/doc#/faquestions/oh7ngo

  2. 继承logback参考 https://blog.csdn.net/u013269532/article/details/89469895


	
	
		%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
	




	${LOG_PATH}/${LOG_FILE}.log
	
		${LOG_PATH}/${LOG_FILE}-%d{yyyy-MM-dd_HH}.%i.zip
		
			10MB
		
	
	
		%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
	






	
	






	

package com.bzjk.platform.dingLog;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

/**

  • 钉钉日志 机器人

  • Created by lincz on 2020/5/18
    */
    @Slf4j
    public class SendErrorMsgAppender extends UnsynchronizedAppenderBase {

    private static final String url = “https://oapi.dingtalk.com/robot/send?access_token=f195cb41a458ea532296a34e17de55adb0353657640bfda59e9e1d85b5e94b3a”;

    private HttpHeaders headers;

    public SendErrorMsgAppender() {
    headers = new HttpHeaders();

     headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
    

    }

    @Override
    public void append(ILoggingEvent event) {
    //监听 ERROR 级别的日志 关键字为 “中转项目”
    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();
    //获取服务器Ip,告知哪台服务器抛异常
    InetAddress address = null;
    try {
    address = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
    e.printStackTrace();
    }
    String ip = address.getHostAddress();
    if (null != ip) {
    sb.append(“服务器:”).append(ip).append("\n");
    }
    sb.append(event.getMessage()).append("\n");
    if (StringUtils.isNotEmpty(throwableMsg)) {
    sb.append(throwableMsg).append("\n");
    }
    int i = 0;
    for (StackTraceElementProxy proxy : stackTraceElementProxy) {
    //只打印40行的堆栈
    if (i < 40) {
    sb.append(proxy.getSTEAsString()).append("\n");
    } else {
    break;
    }
    i++;
    }
    } else {
    sb.append(event.getFormattedMessage());
    }
    String msg = sb.toString();
    if (StringUtils.isNotEmpty(msg)) {
    sendMsgToDingDing(msg);
    }
    }
    }

    /**

    • @param msg

    • @return
      */
      private Map sendMsgToDingDing(String msg) {
      RestTemplate restTemplate = new RestTemplate();
      ObjectMapper objectMapper = new ObjectMapper();
      Text text = new Text();
      text.setContent(msg);
      DdMsgBody msgBody = DdMsgBody.builder().msgtype(“text”).text(text).build();
      String json = null;
      try {
      json = objectMapper.writeValueAsString(msgBody);
      } catch (JsonProcessingException e) {
      //不记录日志,有可能死循环
      //log.error(“error”, e);
      }
      if (null == json) {
      return null;
      }

      HttpEntity formEntity = new HttpEntity<>(json, headers);
      Map result = restTemplate.postForObject(url, formEntity, Map.class);
      return result;
      }

    @Builder
    @Data
    private static class DdMsgBody {
    private String msgtype;
    private Text text;
    }

    @Data
    private class Text {
    private String content;
    }
    }

/**
* 测试 钉钉日志
*/
@Test
public void dingLog() {
//打到钉钉上
String smallOrderId = “1”;
logger.error(“中转项目->>ZeroGzController->>getSmallOrderInfo->>小程序订单不存在 参数 smallOrderId={}”, smallOrderId);
}

你可能感兴趣的:(java)