using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using log4net;
namespace CncSimulator.Core
{
public class LogEntry
{
public DateTime Timestamp { get; set; }
public int DeviceCount { get; set; }
public string KeyData { get; set; }
public string FullJson { get; set; }
public long DurationMs { get; set; }
}
/// 日志记录器:内存环形缓冲 + 文件日志输出
public class LogRecorder
{
private readonly int _capacity;
private readonly List _buffer = new List();
private readonly object _lock = new object();
private static readonly ILog _logger = LogManager.GetLogger(typeof(LogRecorder));
public LogRecorder(int capacity = 200)
{
_capacity = capacity;
}
public void Record(int deviceCount, string keyData, string fullJson, long durationMs)
{
var entry = new LogEntry
{
Timestamp = DateTime.Now,
DeviceCount = deviceCount,
KeyData = keyData,
FullJson = fullJson,
DurationMs = durationMs
};
lock (_lock)
{
_buffer.Add(entry);
if (_buffer.Count > _capacity) _buffer.RemoveAt(0);
}
// 触发日志到文件输出
_logger.Info($"[{entry.Timestamp:yyyy-MM-dd HH:mm:ss}] D={deviceCount} Key={keyData} Dur={durationMs}ms");
}
public List GetRecentLogs(int count)
{
lock (_lock)
{
return _buffer.Skip(Math.Max(0, _buffer.Count - count)).Take(count).ToList();
}
}
public LogEntry GetLatest()
{
lock (_lock)
{
return _buffer.Count == 0 ? null : _buffer[_buffer.Count - 1];
}
}
}
}