SystemLog.cs 1.88 KB
using System.Collections.Concurrent;

namespace DataAcquisition.Common.Utils
{
    public class SystemLog
    {
        private static readonly SystemLog _instance = new();
        private readonly ConcurrentQueue<LogVM> _queue = new();

        /// <summary>
        /// 获取日志对象实例
        /// </summary>
        public static SystemLog Instance => _instance;

        /// <summary>
        /// 日志队列包含的元素数
        /// </summary>
        public int Count => _queue.Count;

        /// <summary>
        /// 日志队列是否为空
        /// </summary>
        public bool IsEmpty => _queue.IsEmpty;

        private SystemLog() { }

        public void Log(string message, StatusCode statusCode)
        {
            _queue.Enqueue(new LogVM
            {
                Message = message,
                StatusCode = statusCode,
                DateTime = DateTime.Now
            });
        }

        public void LogInfo(string message)
        {
            Log(message, StatusCode.Info);
        }

        public void LogWarning(string message)
        {
            Log(message, StatusCode.Warning);
        }

        public void LogError(string message)
        {
            Log(message, StatusCode.Error);
        }

        public void LogSuccess(string message)
        {
            Log(message, StatusCode.Success);
        }

        /// <summary>
        /// 获取一条日志
        /// </summary>
        /// <returns></returns>
        public LogVM? GetLog()
        {
            _queue.TryDequeue(out LogVM? log);
            return log;
        }
    }

    public class LogVM
    {
        public string Message { get; set; } = null!;

        public StatusCode StatusCode { get; set; }

        public DateTime DateTime { get; set; }
    }

    public enum StatusCode
    {
        Success = 200,
        Info,
        Warning,
        Error = 500,
    }
}