using System.Threading.Tasks; using System.Threading; using AIK.Service.IService; using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AIK.Service.Service { public class LogService : ILogService { private readonly ILogger _logger; private readonly ConcurrentQueue _logBuffer; private readonly int _maxBufferSize = 1000; public LogService(ILogger logger) { _logger = logger; _logBuffer = new ConcurrentQueue(); } public void LogDebug(string message, params object[] args) { _logger.LogDebug(message, args); AddToBuffer("DEBUG", string.Format(message, args)); } public void LogInformation(string message, params object[] args) { _logger.LogInformation(message, args); AddToBuffer("INFO", string.Format(message, args)); } public void LogWarning(string message, params object[] args) { _logger.LogWarning(message, args); AddToBuffer("WARN", string.Format(message, args)); } public void LogError(Exception? exception, string message, params object[] args) { _logger.LogError(exception, message, args); AddToBuffer("ERROR", $"{string.Format(message, args)} - {exception}"); } public void LogError(string message, params object[] args) { _logger.LogError(message, args); AddToBuffer("ERROR", string.Format(message, args)); } private void AddToBuffer(string level, string message) { var logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [{level}] {message}"; _logBuffer.Enqueue(logEntry); // 保持缓冲区大小 while (_logBuffer.Count > _maxBufferSize && _logBuffer.TryDequeue(out _)) ; } public IReadOnlyList GetRecentLogs(int maxCount = 100) { return _logBuffer.Take(maxCount).ToList().AsReadOnly(); } public Task UploadLogsAsync() { // 上传逻辑在单独的LogUploadService中实现 //预留日志记录上传服务器 return Task.FromResult(true); } public void ClearBuffer() { while (_logBuffer.TryDequeue(out _)) ; } } }