irc-netcore-api/IRaCIS.Core.Application/Helper/OtherTool/WeComNotifier.cs

88 lines
2.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
using System.Net;
using System.Threading.Tasks;
using IdentityModel;
namespace IRaCIS.Core.Application.Helper.OtherTool;
public static class WeComNotifier
{
public static async Task SendErrorAsync(string webhook, string env, string userName,string api,string json, Exception ex, params string[] atUsers)
{
try
{
var client = new RestClient();
var request = new RestRequest(webhook, Method.Post);
string hostName = Dns.GetHostName();
string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
var stack = ex.StackTrace ?? "无堆栈信息";
stack = stack.Replace("\n", "\n> "); // 每行变成引用防止markdown断裂
if (stack.Length > 1000)
stack = stack.Substring(0, 1000) + "...(已截断)";
string atText = "";
if (atUsers != null && atUsers.Any())
{
foreach (var u in atUsers)
{
atText += $" <@{u}>"; // 注意空格分隔
}
}
//> **运行环境:** < font color = ""comment"" >{ EnvironmentName}</ font > danger danger warning
var markdown = $@"## 🚨 系统异常告警
> {atText}
> **部署环境:** [{env}]({env})
> **服务器:** {hostName}
> **发生时间:** {time}
> **操作人:** {userName}
> **接口地址:** {api}
### ❗ 异常信息
<font color=""warning"">{ex.Message}</font>
>**📦 请求数据JSON 格式):**
```json
{json}
```
### 堆栈信息(部分)
> <font color=""comment"">{stack}</font>
";
var payload = new
{
msgtype = "markdown",
markdown = new
{
content = markdown
}
};
request.AddHeader("Content-Type", "application/json");
request.AddStringBody(JsonConvert.SerializeObject(payload), DataFormat.Json);
var response = await client.ExecuteAsync(request);
if (!response.IsSuccessful)
{
Log.Logger.Error($"企业微信通知失败: {response.StatusCode} {response.ErrorMessage}");
}
}
catch (Exception notifyEx)
{
Log.Logger.Error("发送企业微信告警异常: " + notifyEx.Message);
}
}
}