package com.qs.mp.framework.monitor;

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.qs.mp.common.utils.StringUtils;
import com.qs.mp.common.utils.WebhookService;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhongcp
 * @Date 2021/10/25
 */
@Slf4j
public class SendErrorMsgAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

  @Override
  public void append(ILoggingEvent event) {
    if (event.getLevel() == Level.ERROR) {
      System.out.println("+++++++发送错误告警：" + event);
      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();
        if (StringUtils.isNotBlank(throwableMsg) && (throwableMsg.startsWith("验证码失效") || throwableMsg.startsWith("重复购买，请稍后再试")
        || throwableMsg.startsWith("盲票已付款，") || throwableMsg.startsWith("盲票已兑奖") || throwableMsg.startsWith("登录用户不存在：")
        || throwableMsg.startsWith("用户不存在/密码错误") || throwableMsg.startsWith("验证码已失效") || throwableMsg.startsWith("您已经助力过了")
        || throwableMsg.startsWith("您已经获取过抽奖码了") || throwableMsg.startsWith("奖品总数值不相同") || throwableMsg.startsWith("包含已兑奖记录的奖品不能从奖级中删除")
        || throwableMsg.startsWith("登录账号不存在") || throwableMsg.startsWith("已选择更高级的渠道,不支持渠道相互嵌套!") || throwableMsg.startsWith("内定人数不能超过100")
        )) {
          return;
        }
        StackTraceElementProxy[] stackTraceElementProxy = iThrowableProxy.getStackTraceElementProxyArray();
        //获取服务器Ip，告知哪台服务器抛异常
        /*String ip = Context.getContext().getIp();
        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.isBlank(msg)) {
        msg = event.toString();
      }
      WebhookService.sendLogAlertMsg(msg);
    }
  }



}
