This commit is contained in:
孙诚
2025-02-27 16:58:21 +08:00
commit 80ab8d76eb
40 changed files with 2482 additions and 0 deletions

View File

@@ -0,0 +1,106 @@
using System.Text;
using Core;
using FluentScheduler;
using Interface.Jobs;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
namespace Service.Jobs;
public class LogTotalNotifyJobRegistry : Registry, ILogTotalNotifyJobRegistry
{
private readonly IConfiguration _configuration;
public LogTotalNotifyJobRegistry(IConfiguration configuration)
{
_configuration = configuration;
Schedule(Job).ToRunEvery(1).Days().At(8, 30);
}
public async void Job()
{
try
{
// await JobExecute();
}
catch (Exception e)
{
Console.WriteLine(e);
await WxNotify.SendCommonAsync($"LogTotalNotifyJobRegistry.Job() error: {e}");
}
}
private async Task JobExecute()
{
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_configuration["Grafana:Token"]}");
var requestBody =
"""
{
"queries": [
{
"datasource": {
"type": "loki",
"uid": "edf5cwf6n6i2oe"
},
"editorMode": "builder",
"expr": "sum by(container_name) (count_over_time({compose_project=~\"dockers|immich|nasrobot|elasticsearch|webui-docker\"} [1h]))",
"queryType": "range",
"refId": "A",
"datasourceId": 2,
"intervalMs": 3600000
}
],
"from": "1708963200000",
"to": "1709049600000"
}
""";
requestBody = requestBody.Replace("1708963200000", DateTime.Today.AddDays(-2).ToUnixTimeMilliseconds().ToString());
requestBody = requestBody.Replace("1709049600000", DateTime.Today.AddDays(-1).ToUnixTimeMilliseconds().ToString());
var content = new StringContent(requestBody, Encoding.UTF8, "application/json");
var response = await client.PostAsync(_configuration["Grafana:LokiUrl"], content);
var result = await response.Content.ReadAsStringAsync();
var jObject = JObject.Parse(result);
var frames = jObject["results"]?["A"]?["frames"];
if (frames == null)
{
throw new Exception("frames is null");
}
var msg = new StringBuilder();
msg.AppendLine($"## {DateTime.Today.AddDays(-1):yyyy-MM-dd}日志明细如下:");
var total = 0;
var kv = new Dictionary<string, int>();
foreach (var item in frames)
{
var name = item["schema"]?["fields"]?.LastOrDefault()?["labels"]?["container_name"]?.ToString();
if (string.IsNullOrEmpty(name))
{
continue;
}
var values = item["data"]?["values"]?.LastOrDefault()?.ToObject<int[]>();
var value = values?.Sum() ?? 0;
total += value;
kv[name] = value;
}
foreach (var (key, value) in kv.OrderByDescending(x => x.Value))
{
msg.AppendLine($"<font color='info'>**{key}**</font>: <font color='warning'>{value}</font>");
}
msg.AppendLine("");
msg.AppendLine($"> **总计**: <font color='warning'>{total}</font>");
await WxNotify.SendCommonAsync(msg.ToString());
}
}