You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
2.0 KiB
C#
67 lines
2.0 KiB
C#
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; }
|
|
}
|
|
|
|
/// <summary>日志记录器:内存环形缓冲 + 文件日志输出</summary>
|
|
public class LogRecorder
|
|
{
|
|
private readonly int _capacity;
|
|
private readonly List<LogEntry> _buffer = new List<LogEntry>();
|
|
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<LogEntry> 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];
|
|
}
|
|
}
|
|
}
|
|
}
|