using System.Net.Http.Headers; using System.Text; using System.Text.Json; using Fake.SyncEx; using InterfaceForward.Domain.Shared.Options; using Serilog; namespace InterfaceForward.Domain.Shared.Helpers; public static class LogHelper { private static FeiShuNoticeOptions _options = null!; public static void Init(FeiShuNoticeOptions options) { _options = options; } public static void Info(string msg, bool isSend = false) { Log.Information(msg); if (!isSend) return; SyncContext.Run(() => NoticeAsync(msg, isSend, "Info")); } public static void Warn(string msg, bool isSend = false) { Log.Warning(msg); if (!isSend) return; SyncContext.Run(() => NoticeAsync(msg, isSend, "Warn")); } public static void Error(string msg, bool isSend = true) { Log.Error(msg); SyncContext.Run(() => NoticeAsync(msg, isSend, "Error")); } public static async Task NoticeAsync(string content, bool isSend, string subTitle = "") { #if DEBUG // 调试模式下不发送通知 return; #endif if (!isSend) { return; } if (_options.Webhook.IsNullOrWhiteSpace()) { Log.Warning("未配置飞书webhook"); return; } var title = subTitle.IsNullOrWhiteSpace() ? _options.TitlePrefix : _options.TitlePrefix + "_" + subTitle; await HandleNoticeAsync(content, title); } private static async Task HandleNoticeAsync(string content, string title) { var message = new { msg_type = "post", content = new { post = new { zh_cn = new { title, content = new List() { new List() { new { tag = "text", text = content + Environment.NewLine } } } } } } }; using var httpClient = new HttpClient(); httpClient.Timeout = TimeSpan.FromSeconds(_options.Timeout); using var httpContent = new StringContent(JsonSerializer.Serialize(message), Encoding.UTF8); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); await httpClient.PostAsync(_options.Webhook, httpContent); } }