itfx/src/InterfaceForward.Domain.Shared/Helpers/LogHelper.cs
2024-12-20 10:55:59 +08:00

98 lines
2.7 KiB
C#

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<object>()
{
new List<object>()
{
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);
}
}