logback 钉钉机器人通知 LogDingDingAppender

package com.wjj.application.config;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;

/**
 * 钉钉logback appender
 *
 * @author hank
 * @apiNote
 *          
            
            
            
                
                ${springProfile} %level\n%m\n%logger\n%ex{1}
                
                
                
                xxxxxxxxxxx
                
                error
                
                xxxxxxxxx
            

            
            
                
                
                    
                
                
                
                
            
 */
public class LogDingDingAppender extends UnsynchronizedAppenderBase {
    private String pattern = "%level\n%m\n%logger\n%ex{1}";
    private PatternLayout layout;
    private String profilesActive = "unknown";
    private String dingdingToken;
    private Level nowLevel = Level.ERROR;
    private String secret;

    @Override
    protected void append(LoggingEvent eventObject) {
        try {
            if(eventObject.getLevel().isGreaterOrEqual(nowLevel)) {
                String toMsg = layout.doLayout(eventObject);
/*                if (null != eventObject.getThrowableProxy() && null != eventObject.getThrowableProxy().getStackTraceElementProxyArray() && eventObject.getThrowableProxy().getStackTraceElementProxyArray().length > 0) {
                    if(null != eventObject.getThrowableProxy().getMessage()){
                        toMsg += "EMsg: "+eventObject.getThrowableProxy().getMessage() + "\n\n";
                    }
                    toMsg += eventObject.getThrowableProxy().getStackTraceElementProxyArray()[0].getSTEAsString();
                }*/
                toDingDing("https://oapi.dingtalk.com/robot/send?access_token="+getDingdingToken(), toMsg);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void start() {
        PatternLayout patternLayout = new PatternLayout();
        patternLayout.setContext(context);
        patternLayout.setPattern(getPattern());
//        patternLayout.setOutputPatternAsHeader(outputPatternAsHeader);
        patternLayout.start();
        this.layout = patternLayout;
        super.start();
    }

    private void toDingDing(String webHookToken, String contentMsg) throws Exception{

        String textMsg="{\"msgtype\": \"text\",\"text\": {\"content\": " + JSON.toJSONString(contentMsg) + "}}";
        //加签
        if(secret != null){
            Long timestamp = System.currentTimeMillis();
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
            webHookToken += "×tamp=" + timestamp + "&sign=" + sign;
        }

        try(CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httppost = new HttpPost(webHookToken);
            httppost.addHeader("Content-Type", "application/json; charset=utf-8");

            StringEntity se = new StringEntity(textMsg, "utf-8");
            httppost.setEntity(se);

            httpclient.execute(httppost);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getProfilesActive() {
        return profilesActive;
    }

    public void setProfilesActive(String profilesActive) {
        this.profilesActive = profilesActive;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    public String getPattern() {
        return pattern;
    }

    public PatternLayout getLayout() {
        return layout;
    }

    public void setLayout(PatternLayout layout) {
        this.layout = layout;
    }

    public String getDingdingToken() {
        return dingdingToken;
    }

    public void setDingdingToken(String dingdingToken) {
        this.dingdingToken = dingdingToken;
    }
    public void setLevel(String level) {
        this.nowLevel = Level.toLevel(level, Level.ERROR);
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }
}

再在logbac-spring.xml加入配置:


    
    
    
        
        ${springProfile} %level\n%m\n%logger\n%ex{1}
        
        
        
        xxxxxxxx
        
        error
        
        xxxxxxxxxxx
    

    
    
        
        
            
        
        
        
        
    

关于配置pattern可以参考 https://blog.csdn.net/huang007guo/article/details/99634135

你可能感兴趣的:(java,spring,boot,spring)