异步、队列写日志文件

这是一个C#实现的日志类,通过队列实现异步写入日志文件,确保日志记录的高效性和同步性。类中包含同步写入日志、错误日志记录以及异步写入日志的方法,并提供了事件通知新日志产生的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SysLogInfo
{
    public class SysLog
    {
        private static System.Collections.Generic.Queue<string> _logBuffer = new System.Collections.Generic.Queue<string>();
        private static bool _isDispose;
        private static string _logPath;
        private static string _logTilte;


        public SysLog(string logTilte)
        {
            _logPath = AppDomain.CurrentDomain.BaseDirectory.Trim() + "log";
            _logTilte = "Log_"+ logTilte + "_";
        }
        

        /// <summary>
        /// 同步写入日志
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="info">信息</param>
        private static void SyncWriteLog(string title, string info)
        {
            AddLog(DateTime.Now, title, info);
            _isDispose = true;
            WriteLog(null);
            OnNewLog(title, info, true);
        }
        /// <summary>
        /// 写入错误日志
        /// </summary>
        /// <param name="logTime">时间</param>
        /// <param name="title">标题</param>
        /// <param name="info">内容</param>
        private static void AddLog(DateTime logTime, string title, string info)
        {
            if (_isDispose) return;
            lock (_logPath)
            {
                try
                {
                    _logBuffer.Enqueue("[" + logTime.ToString(TimeFormat) + "]  " + title + "  " + info + Environment.NewLine);
                }
                catch
                {
                    // ignored
                }
            }
        }

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="info">信息</param>
        public void WriteLogInfo(string info, string title="")
        {
            _logPath = string.IsNullOrWhiteSpace(_logPath) ? AppDomain.CurrentDomain.BaseDirectory.Trim() + "log" : _logPath;
            AddLog(DateTime.Now, title, info);
            System.Threading.ThreadPool.QueueUserWorkItem(WriteLog);
            OnNewLog(title, info, false);
        }

        private static bool _isAdd;
        private static void WriteLog(object obj)
        {
            if (_isAdd) return;
            _isAdd = true;
            lock (_logPath)
            {
                string logFile = LogPath + "\\" + LogTile + DateTime.Now.ToString("yyyyMMdd") + ".log";
                try
                {
                    using (var sw = new StreamWriter(logFile, true, Encoding.Default))
                    {
                        while (_logBuffer.Count > 0)
                        {
                            try
                            {
                                sw.Write(_logBuffer.Peek());
                                _logBuffer.Dequeue();
                            }
                            catch
                            {
                                break;
                            }
                        }
                        sw.Close();
                        sw.Dispose();
                    }
                }
                catch
                {
                    // ignored
                }
            }
            _isAdd = false;
        }

        
        /// <summary>
        /// 获取或设置日志文件存放路径
        /// </summary>
        public static string LogPath
        {
            get
            {
                if (!Directory.Exists(_logPath))
                {
                    Directory.CreateDirectory(_logPath);
                }
                return _logPath;
            }
            set { _logPath = value; }
        }
        public static string LogTile
        {
            get
            {
                return _logTilte;
            }
            set
            {
                _logTilte = value;
            }
        }
        /// <summary>
        /// 时间格式
        /// </summary>
        public static string TimeFormat { get; set; } = "HH:mm:ss,fff";

        /// <summary>
        /// 有新日志产生时
        /// </summary>
        public static event ExceptionHandler NewLog;
        /// <summary>
        /// 有新日志产生是触发
        /// </summary>
        /// <param name="title"></param>
        /// <param name="info"></param>
        /// <param name="isTerminating"></param>
        private static void OnNewLog(string title, string info, bool isTerminating)
        {
            NewLog?.Invoke(title, info, isTerminating);
        }
        /// <summary>
        /// 异常事件
        /// </summary>
        public delegate void ExceptionHandler(string title, string info, bool isTerminating);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值