using System; using System.Collections.Generic; using System.Net; using System.Net.Http.Json; using System.Threading.Tasks; using ColdMint.scripts.debug; using Godot; using HttpClient = System.Net.Http.HttpClient; namespace ColdMint.scripts.openObserve; /// /// LogCollector /// 日志收集器 /// public static class LogCollector { private static readonly List _logDataList = []; /// /// Automatic upload threshold /// 自动上传的阈值 /// /// ///An attempt is made to upload logs when messages reach this number. ///当消息到达此数量后将尝试上传日志。 /// public static int UploadThreshold { get; set; } = 50; private static bool lockList = false; /// /// httpClient /// Http客户 /// private static HttpClient? _httpClient; private static string? _orgId; /// /// UpdateHttpClient /// 更新Http客户端 /// /// public static void UpdateHttpClient(OpenObserve openObserve) { if (openObserve.Address == null || openObserve.AccessToken == null || openObserve.OrgId == null) { return; } var httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(openObserve.Address); //Add a Cookie to the request header //添加Cookie到请求头 var cookie = new Cookie("auth_tokens", "{\"access_token\":\"Basic " + openObserve.AccessToken + "\",\"refresh_token\":\"\"}"); httpClient.DefaultRequestHeaders.Add("Cookie", cookie.ToString()); _httpClient = httpClient; _orgId = openObserve.OrgId; } /// /// Push log /// 推送日志 /// /// private static async Task PostLog(List logRequestBean) { if (_httpClient == null) { return; } lockList = true; GD.Print("开始上传"); var httpResponseMessage = await _httpClient.PostAsJsonAsync("/api/" + _orgId + "/game/_json", logRequestBean); if (httpResponseMessage.IsSuccessStatusCode) { _logDataList.RemoveRange(0, logRequestBean.Count); } else { GD.Print("上传失败" + httpResponseMessage.StatusCode.ToString()); } lockList = false; } public static void Push(LogData logData) { _logDataList.Add(logData); GD.Print("上传吗" + lockList + "长度为" + _logDataList.Count + "阈值" + UploadThreshold); if (!lockList && _logDataList.Count > UploadThreshold) { //执行上传 GD.Print("上传"); PostLog(_logDataList.GetRange(0, UploadThreshold)); } } } public class LogData { /// /// The AppId of this application /// 此应用的AppId /// public string? AppId { get; set; } /// /// message /// 消息 /// public string? Message { get; set; } }