root 1 month ago
parent
commit
3496facbb0
  1. 34
      LTEMvcApp/Controllers/WebSocketController.cs
  2. 42
      LTEMvcApp/Services/WebSocketManagerService.cs
  3. 80
      LTEMvcApp/Views/Home/Logs.cshtml

34
LTEMvcApp/Controllers/WebSocketController.cs

@ -538,6 +538,32 @@ namespace LTEMvcApp.Controllers
}
}
/// <summary>
/// 添加测试日志数据
/// </summary>
/// <returns>操作结果</returns>
[HttpPost("logs/add-test-data")]
public ActionResult AddTestLogData()
{
try
{
var testLogs = new List<LTELog>
{
};
// 手动添加到日志缓存
_webSocketManager.AddLogsToCache(testLogs);
return Ok(new { message = $"已添加 {testLogs.Count} 条测试日志" });
}
catch (Exception ex)
{
_logger.LogError(ex, "添加测试日志数据时发生错误");
return StatusCode(500, new { message = "添加测试日志失败", error = ex.Message });
}
}
/// <summary>
/// 使用 Server-Sent Events (SSE) 实时推送全局日志
/// </summary>
@ -562,13 +588,20 @@ namespace LTEMvcApp.Controllers
try
{
var initialLogs = _webSocketManager.GetLogCache()?.ToList() ?? new List<LTELog>();
_logger.LogInformation("StreamLogs: 获取到初始日志 {Count} 条", initialLogs.Count);
if (initialLogs.Any())
{
_logger.LogInformation("StreamLogs: 发送历史日志事件,日志数量: {Count}", initialLogs.Count);
await SendSseEvent("history", new { logs = initialLogs, totalCount = initialLogs.Count });
await Response.Body.FlushAsync(cancellationToken);
lastLogCount = initialLogs.Count;
lastLogs = initialLogs.ToList(); // 保存副本用于比较
}
else
{
_logger.LogInformation("StreamLogs: 没有历史日志数据");
}
}
catch (Exception ex)
{
@ -591,6 +624,7 @@ namespace LTEMvcApp.Controllers
if (newLogs.Any())
{
_logger.LogInformation("StreamLogs: 发送新日志事件,新增日志数量: {NewCount}, 总日志数量: {TotalCount}", newLogs.Count, currentLogs.Count);
await SendSseEvent("new_logs", new {
logs = newLogs,
totalCount = currentLogs.Count,

42
LTEMvcApp/Services/WebSocketManagerService.cs

@ -472,6 +472,48 @@ namespace LTEMvcApp.Services
// 可以在这里添加其他重置逻辑
}
/// <summary>
/// 手动添加日志到缓存
/// </summary>
/// <param name="log">日志对象</param>
public void AddLogToCache(LTELog log)
{
if (log != null)
{
_logCache.Enqueue(log);
_logger.LogInformation("手动添加日志到缓存: {Layer} - {Message}", log.Layer, log.Message);
// 维持缓存大小
while (_logCache.Count > LogCacheSize)
{
_logCache.TryDequeue(out _);
}
}
}
/// <summary>
/// 手动添加多个日志到缓存
/// </summary>
/// <param name="logs">日志列表</param>
public void AddLogsToCache(List<LTELog> logs)
{
if (logs != null && logs.Any())
{
foreach (var log in logs)
{
_logCache.Enqueue(log);
}
_logger.LogInformation("手动添加 {Count} 条日志到缓存", logs.Count);
// 维持缓存大小
while (_logCache.Count > LogCacheSize)
{
_logCache.TryDequeue(out _);
}
}
}
#endregion
#region 私有方法

80
LTEMvcApp/Views/Home/Logs.cshtml

@ -218,6 +218,7 @@
<div class="control-buttons">
<button class="btn-small" id="clear-logs-btn" title="清空日志">清空</button>
<button class="btn-small" id="reset-logs-btn" title="重置日志">重置</button>
<button class="btn-small" id="add-test-data-btn" title="添加测试数据">测试</button>
<button class="btn-small" id="reconnect-btn" title="重新连接">重连</button>
</div>
</div>
@ -251,6 +252,7 @@
const infoMessage = document.getElementById('info-message');
const clearLogsBtn = document.getElementById('clear-logs-btn');
const resetLogsBtn = document.getElementById('reset-logs-btn');
const addTestDataBtn = document.getElementById('add-test-data-btn');
const reconnectBtn = document.getElementById('reconnect-btn');
let allLogsData = [];
@ -410,30 +412,59 @@
});
eventSource.addEventListener('history', function(event) {
console.log("接收到历史日志...");
const data = JSON.parse(event.data);
updateLogList(data.logs);
showInfo(`加载了 ${data.logs.length} 条历史日志`);
console.log("接收到历史日志...", event.data);
try {
const data = JSON.parse(event.data);
console.log("历史日志数据:", data);
if (data.logs && Array.isArray(data.logs)) {
updateLogList(data.logs);
showInfo(`加载了 ${data.logs.length} 条历史日志`);
} else {
console.warn("历史日志数据格式不正确:", data);
showError("历史日志数据格式不正确");
}
} catch (error) {
console.error("解析历史日志数据失败:", error);
showError("解析历史日志数据失败: " + error.message);
}
});
eventSource.addEventListener('new_logs', function(event) {
console.log("接收到新日志...");
const data = JSON.parse(event.data);
updateLogList(data.logs);
console.log("接收到新日志...", event.data);
try {
const data = JSON.parse(event.data);
console.log("新日志数据:", data);
if (data.logs && Array.isArray(data.logs)) {
updateLogList(data.logs);
} else {
console.warn("新日志数据格式不正确:", data);
}
} catch (error) {
console.error("解析新日志数据失败:", error);
showError("解析新日志数据失败: " + error.message);
}
});
eventSource.addEventListener('reset', function(event) {
console.log("日志缓存已重置");
const data = JSON.parse(event.data);
clearLogsDisplay();
showInfo('日志缓存已重置');
try {
const data = JSON.parse(event.data);
clearLogsDisplay();
showInfo('日志缓存已重置');
} catch (error) {
console.error("解析重置事件数据失败:", error);
}
});
eventSource.addEventListener('error', function(event) {
console.log("接收到错误事件");
const data = JSON.parse(event.data);
updateConnectionStatus('error', '连接错误');
showError(`连接错误: ${data.message}`);
try {
const data = JSON.parse(event.data);
updateConnectionStatus('error', '连接错误');
showError(`连接错误: ${data.message}`);
} catch (error) {
console.error("解析错误事件数据失败:", error);
}
});
eventSource.addEventListener('disconnected', function(event) {
@ -444,9 +475,13 @@
eventSource.addEventListener('fatal_error', function(event) {
console.error("致命错误");
const data = JSON.parse(event.data);
updateConnectionStatus('error', '服务器错误');
showError(`服务器错误: ${data.message}`);
try {
const data = JSON.parse(event.data);
updateConnectionStatus('error', '服务器错误');
showError(`服务器错误: ${data.message}`);
} catch (error) {
console.error("解析致命错误数据失败:", error);
}
});
eventSource.onerror = function (err) {
@ -515,6 +550,19 @@
}
});
addTestDataBtn.addEventListener('click', function() {
fetch('/api/websocket/logs/add-test-data', { method: 'POST' })
.then(response => response.json())
.then(data => {
if (data.message) {
showInfo(data.message);
}
})
.catch(error => {
showError('添加测试数据失败: ' + error.message);
});
});
reconnectBtn.addEventListener('click', function() {
reconnectAttempts = 0; // 重置重连计数
connectSSE();

Loading…
Cancel
Save