1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
| public class WecomLogAlertAppender extends AppenderBase<ILoggingEvent> {
private static final ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(2, 8, 60_000, TimeUnit.MILLISECONDS , new LinkedBlockingQueue<>(1000), (Runnable r) -> { Thread thread = new Thread(r); thread.setName("WeChatAppender-" + thread.getId()); return thread; }, new ThreadPoolExecutor.AbortPolicy());
private static final OkHttpClient client = new OkHttpClient.Builder() .connectionPool(new ConnectionPool(5, 5, TimeUnit.MINUTES)) .connectTimeout(5, TimeUnit.SECONDS) .writeTimeout(5, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .retryOnConnectionFailure(true) .build(); private static Environment environment; private final ObjectMapper mapper = new ObjectMapper(); private final String webhookUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=";
private static Set<Level> getLogLevels() { String levelConfig = Optional.ofNullable(getEnvironment()).map(env -> env.getProperty("whisper.log.levels")).orElse("ERROR"); return Arrays.stream(levelConfig.split(",")) .map(String::trim) .map(String::toUpperCase) .map(Level::toLevel) .collect(Collectors.toSet()); }
private static Environment getEnvironment() { if (environment == null) { synchronized (WecomLogAlertAppender.class) { if (environment == null) { environment = SpringContextUtil.getBean(Environment.class); } } } return environment; }
private static String getRobotKey() { if (Objects.isNull(getEnvironment())) { return null; } return getEnvironment().getProperty("whisper.robotKey"); }
private static boolean getEnable() { if (Objects.isNull(getEnvironment())) { return Boolean.FALSE; } try { return Boolean.parseBoolean(getEnvironment().getProperty("whisper.enable")); } catch (Exception e) { return Boolean.FALSE; } }
private static String getProfiles() { if (Objects.isNull(getEnvironment())) { return null; } return getEnvironment().getProperty("spring.profiles.active"); }
@Override protected void append(ILoggingEvent event) { if (!getEnable()) { return; } if (StringUtils.isBlank(getRobotKey())) { return; } if (!getLogLevels().contains(event.getLevel())) { return; } THREAD_POOL_EXECUTOR.execute(() -> { try { String json = mapper.writeValueAsString(createMessage(event)); RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8")); Request request = new Request.Builder() .url(webhookUrl + getRobotKey()) .post(body) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { addError("Failed to send log message to WeChat:", new Exception(response.body().string())); } } } catch (JsonProcessingException e) { addError("Failed to convert log message to JSON", e); } catch (Exception e) { addError("Failed to send log message to WeChat", e); } }); }
private Map<String, Object> createMessage(ILoggingEvent event) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String exceptionMessage = getExceptionMessage(event);
String color; if (event.getLevel() == Level.ERROR) { color = "#F24956"; } else if (event.getLevel() == Level.WARN) { color = "#F2AA27"; } else if (event.getLevel() == Level.INFO) { color = "#000000"; } else { color = "#A0A0A0"; }
String content = String.format("[%s] <font color=\"%s\">**%s**</font> %s\n> %s \n%s", getProfiles(), color, event.getLevel(), sdf.format(event.getTimeStamp()), event.getFormattedMessage(), exceptionMessage.substring(0, Math.min(exceptionMessage.length(), 1000)));
Map<String, Object> message = new HashMap<>(); message.put("msgtype", "markdown"); Map<String, String> markdown = new HashMap<>(); markdown.put("content", content.substring(0, Math.min(content.length(), 4095))); message.put("markdown", markdown);
return message; }
private String getExceptionMessage(ILoggingEvent event) { IThrowableProxy throwableProxy = event.getThrowableProxy(); if (throwableProxy != null) { StringBuilder sb = new StringBuilder(); sb.append(throwableProxy.getClassName()).append(": ").append(throwableProxy.getMessage()).append("\n"); for (StackTraceElementProxy element : throwableProxy.getStackTraceElementProxyArray()) { sb.append(element.toString()).append("\n"); } return sb.toString(); } return ""; } }
|