You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
84 lines
2.5 KiB
84 lines
2.5 KiB
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<LogService> _logger;
|
|
private readonly ConcurrentQueue<string> _logBuffer;
|
|
private readonly int _maxBufferSize = 1000;
|
|
|
|
public LogService(ILogger<LogService> logger)
|
|
{
|
|
_logger = logger;
|
|
_logBuffer = new ConcurrentQueue<string>();
|
|
}
|
|
|
|
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<string> GetRecentLogs(int maxCount = 100)
|
|
{
|
|
return _logBuffer.Take(maxCount).ToList().AsReadOnly();
|
|
}
|
|
|
|
public Task<bool> UploadLogsAsync()
|
|
{
|
|
// 上传逻辑在单独的LogUploadService中实现
|
|
|
|
//预留日志记录上传服务器
|
|
return Task.FromResult(true);
|
|
}
|
|
|
|
public void ClearBuffer()
|
|
{
|
|
while (_logBuffer.TryDequeue(out _)) ;
|
|
}
|
|
}
|
|
}
|
|
|