2508271256

HeartbeatSender添加Try-Catch與Writelog
This commit is contained in:
jasonchenwork 2025-08-27 12:57:34 +08:00
parent 5ddd093273
commit 2466c8cb6a

View File

@ -18,7 +18,7 @@ public class heartbeatSender
private string branchName = "";
private string heartbeatDomain = "";
private CancellationTokenSource? cancellationTokenSource;
public static Dictionary<string, string> DbData= new Dictionary<string, string>() ;
public static Dictionary<string, string> DbData = new Dictionary<string, string>();
public heartbeatSender()
{
this.heartbeatDomain = Utils.Env.Get("HeartBeatUrl", "");
@ -51,6 +51,7 @@ public class heartbeatSender
catch (Exception ex)
{
Console.WriteLine($"心跳任務錯誤:{ex.Message}");
WriteLog(ex.Message);
await Task.Delay(5000); // 錯誤後延遲再跑
}
}
@ -58,109 +59,212 @@ public class heartbeatSender
public void Stop()
{
cancellationTokenSource?.Cancel();
Console.WriteLine("心跳任務已停止");
try
{
cancellationTokenSource?.Cancel();
Console.WriteLine("心跳任務已停止");
}
catch (Exception ex)
{
Console.WriteLine($"心跳任務錯誤:{ex.Message}");
WriteLog(ex.Message);
}
}
public async Task<bool> LoginAndGetTokenAsync()
{
var url = $"{heartbeatDomain.TrimEnd('/')}/api/room/receiveRegister";
var loginPayload = new
try
{
email = "MachineKTV@gmail.com",
password = "aa147258-"
};
var result = await SendPostAsync<JsonElement>(url, loginPayload);
if (result.ValueKind == JsonValueKind.Object &&
result.TryGetProperty("data", out JsonElement data))
{
token = data.GetProperty("token").GetString()!;
branchName = data.GetProperty("branch_name").GetString()!;
var Dbdatas = data.GetProperty("other_set");
if (Dbdatas.ValueKind == JsonValueKind.Object)
var url = $"{heartbeatDomain.TrimEnd('/')}/api/room/receiveRegister";
var loginPayload = new
{
foreach (JsonProperty property in Dbdatas.EnumerateObject())
email = "MachineKTV@gmail.com",
password = "aa147258-"
};
var result = await SendPostAsync<JsonElement>(url, loginPayload);
if (result.ValueKind == JsonValueKind.Object &&
result.TryGetProperty("data", out JsonElement data))
{
token = data.GetProperty("token").GetString()!;
branchName = data.GetProperty("branch_name").GetString()!;
var Dbdatas = data.GetProperty("other_set");
if (Dbdatas.ValueKind == JsonValueKind.Object)
{
DbData.Add(property.Name.ToString(), property.Value.ToString());
foreach (JsonProperty property in Dbdatas.EnumerateObject())
{
DbData.Add(property.Name.ToString(), property.Value.ToString());
}
}
return true;
}
return true;
return false;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return default;
}
return false;
}
public async Task SendHeartbeatAsync()
{
var url = $"{heartbeatDomain.TrimEnd('/')}/api/room/heartbeat";
string hostName = Dns.GetHostName();
var heartbeatPayload = new
try
{
branch_name = branchName,
hostname = "PC" + hostName[^3..],
ip = GetLocalIPv4(),
cpu = GetCpuUsage(),
memory = GetTotalMemoryInMB(),
disk = GetDiskTotalSizeInGB()
};
var url = $"{heartbeatDomain.TrimEnd('/')}/api/room/heartbeat";
string hostName = Dns.GetHostName();
var heartbeatPayload = new
{
branch_name = branchName,
hostname = "PC" + hostName[^3..],
ip = GetLocalIPv4(),
cpu = GetCpuUsage(),
memory = GetTotalMemoryInMB(),
disk = GetDiskTotalSizeInGB()
};
await SendPostAsync<JsonElement>(url, heartbeatPayload, token);
Console.WriteLine($"心跳送出成功: {DateTime.Now:HH:mm:ss}");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return;
}
await SendPostAsync<JsonElement>(url, heartbeatPayload, token);
Console.WriteLine($"心跳送出成功: {DateTime.Now:HH:mm:ss}");
}
private async Task<T?> SendPostAsync<T>(string url, object payload, string? bearerToken = null)
{
var json = JsonSerializer.Serialize(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, url)
try
{
Content = content
};
var json = JsonSerializer.Serialize(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
if (!string.IsNullOrWhiteSpace(bearerToken))
var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = content
};
if (!string.IsNullOrWhiteSpace(bearerToken))
{
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearerToken);
}
var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseJson = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(responseJson);
}
catch (Exception ex)
{
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearerToken);
Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return default(T);
}
var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseJson = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(responseJson);
}
private static string GetLocalIPv4()
{
foreach (var ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
try
{
if (ip.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(ip))
return ip.ToString();
foreach (var ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(ip))
return ip.ToString();
}
return "127.0.0.1";
}
return "127.0.0.1";
catch (Exception ex)
{
Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return "";
}
}
private float GetCpuUsage()
{
using var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
cpuCounter.NextValue();
Thread.Sleep(100);
return cpuCounter.NextValue();
try
{
using var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
cpuCounter.NextValue();
Thread.Sleep(100);
return cpuCounter.NextValue();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return float.NaN;
}
}
private float GetTotalMemoryInMB()
{
var ci = new ComputerInfo();
return (ci.TotalPhysicalMemory - ci.AvailablePhysicalMemory) / 1024f;
try
{
var ci = new ComputerInfo();
return (ci.TotalPhysicalMemory - ci.AvailablePhysicalMemory) / 1024f;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return float.NaN;
}
}
private float GetDiskTotalSizeInGB(string driveLetter = "C")
{
var drive = new DriveInfo(driveLetter);
return drive.TotalSize / (1024f * 1024f * 1024f);
try
{
var drive = new DriveInfo(driveLetter);
return drive.TotalSize / (1024f * 1024f * 1024f);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return float.NaN;
}
}
public static void WriteLog(string message)
{
// 指定日志文件的路径
string logFilePath = Path.Combine(Application.StartupPath, "txt", "mainlog.txt");
try
{
// 使用 StreamWriter 来向日志文件追加文本
using (StreamWriter writer = new StreamWriter(logFilePath, true))
{
writer.WriteLine(String.Format("[{0}] {1}", DateTime.Now, message));
}
}
catch (Exception ex)
{
// 如果写入日志文件时发生错误,这里可以处理这些异常
// 例如:打印到控制台
Console.WriteLine(String.Format("Error writing to log file: {0}", ex.Message));
}
}
}