初始化
Some checks failed
Some checks failed
This commit is contained in:
151
backend/Controllers/MonitorController.cs
Normal file
151
backend/Controllers/MonitorController.cs
Normal file
@@ -0,0 +1,151 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace HardwarePerformanceAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/monitor")]
|
||||
public class MonitorController : ControllerBase
|
||||
{
|
||||
private readonly ILogger<MonitorController> _logger;
|
||||
private readonly string _logDirectory;
|
||||
|
||||
public MonitorController(ILogger<MonitorController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
// 设置日志存储目录
|
||||
_logDirectory = Path.Combine(Directory.GetCurrentDirectory(), "logs", "monitor");
|
||||
|
||||
// 确保目录存在
|
||||
if (!Directory.Exists(_logDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(_logDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost("report")]
|
||||
public async Task<IActionResult> ReportData([FromBody] JsonElement data)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 获取客户端IP
|
||||
var clientIp = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||
|
||||
// 获取用户代理
|
||||
var userAgent = Request.Headers["User-Agent"].ToString() ?? "unknown";
|
||||
|
||||
// 添加元数据
|
||||
var reportData = new
|
||||
{
|
||||
Timestamp = DateTime.UtcNow,
|
||||
ClientIp = clientIp,
|
||||
UserAgent = userAgent,
|
||||
Data = data
|
||||
};
|
||||
|
||||
// 生成文件名(按日期分类)
|
||||
var fileName = $"monitor_{DateTime.UtcNow:yyyyMMdd}.json";
|
||||
var filePath = Path.Combine(_logDirectory, fileName);
|
||||
|
||||
// 将数据写入文件
|
||||
var json = JsonSerializer.Serialize(reportData, new JsonSerializerOptions
|
||||
{
|
||||
WriteIndented = true
|
||||
});
|
||||
|
||||
await System.IO.File.AppendAllTextAsync(filePath, json + Environment.NewLine + Environment.NewLine);
|
||||
|
||||
_logger.LogInformation("Monitor data received from {ClientIp}", clientIp);
|
||||
|
||||
return Ok(new { success = true, message = "Data reported successfully" });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error processing monitor data");
|
||||
return StatusCode(500, new { success = false, message = "Internal server error" });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("stats")]
|
||||
public IActionResult GetStats()
|
||||
{
|
||||
try
|
||||
{
|
||||
var stats = new
|
||||
{
|
||||
ReportsCount = CountReports(),
|
||||
LastReportTime = GetLastReportTime(),
|
||||
ErrorCount = CountReportsByType("error"),
|
||||
PerformanceCount = CountReportsByType("performance")
|
||||
};
|
||||
|
||||
return Ok(stats);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error getting monitor stats");
|
||||
return StatusCode(500, new { success = false, message = "Internal server error" });
|
||||
}
|
||||
}
|
||||
|
||||
private int CountReports()
|
||||
{
|
||||
var today = DateTime.UtcNow.ToString("yyyyMMdd");
|
||||
var filePath = Path.Combine(_logDirectory, $"monitor_{today}.json");
|
||||
|
||||
if (!System.IO.File.Exists(filePath))
|
||||
return 0;
|
||||
|
||||
var content = System.IO.File.ReadAllText(filePath);
|
||||
var lines = content.Split(new[] { Environment.NewLine + Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
|
||||
return lines.Length;
|
||||
}
|
||||
|
||||
private DateTime? GetLastReportTime()
|
||||
{
|
||||
var today = DateTime.UtcNow.ToString("yyyyMMdd");
|
||||
var filePath = Path.Combine(_logDirectory, $"monitor_{today}.json");
|
||||
|
||||
if (!System.IO.File.Exists(filePath))
|
||||
return null;
|
||||
|
||||
var fileInfo = new FileInfo(filePath);
|
||||
return fileInfo.LastWriteTimeUtc;
|
||||
}
|
||||
|
||||
private int CountReportsByType(string type)
|
||||
{
|
||||
var today = DateTime.UtcNow.ToString("yyyyMMdd");
|
||||
var filePath = Path.Combine(_logDirectory, $"monitor_{today}.json");
|
||||
|
||||
if (!System.IO.File.Exists(filePath))
|
||||
return 0;
|
||||
|
||||
var content = System.IO.File.ReadAllText(filePath);
|
||||
var lines = content.Split(new[] { Environment.NewLine + Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
int count = 0;
|
||||
foreach (var line in lines)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(line);
|
||||
if (document.RootElement.TryGetProperty("Data", out var dataElement))
|
||||
{
|
||||
if (dataElement.TryGetProperty("type", out var typeElement) &&
|
||||
typeElement.GetString()?.Contains(type) == true)
|
||||
{
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 忽略解析错误
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user