.NET多线程高并发写入日志

   /// <summary>
        /// 写入日志文件
        /// </summary>
        //读写锁,当资源处于写入模式时,其他线程写入需要等待本次写入结束之后才能继续写入
        static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
        public static void WriteLog(string strLog)
        {
            if (!strLog.StartsWith("error"))
                Console.WriteLine(strLog);
            else
                Console.WriteLine("出现错误,详情请查看日志文件");
            string sFilePath = "log\\";
            if (!Directory.Exists(sFilePath))//验证路径是否存在
            {
                Directory.CreateDirectory(sFilePath);
                //不存在则创建
            }
            string sFileName = $"log\\{DateTime.Now.ToString("yyyy-MM-dd")}.log";
            string errorFilename = $"log\\{DateTime.Now.ToString("yyyy-MM-dd")}error.log";
            try
            {
                LogWriteLock.EnterWriteLock();
                if (!strLog.StartsWith("error"))
                    File.AppendAllText(sFileName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "   ---   " + strLog + "\r\n");
                else
                    File.AppendAllText(errorFilename, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "   ---   " + strLog + "\r\n");
            }
            catch (Exception ex)
            {

                throw;
            }
            finally
            {
                //退出写入模式,释放资源占用
                //注意:一次请求对应一次释放
                //      若释放次数大于请求次数将会触发异常[写入锁定未经保持即被释放]
                //      若请求处理完成后未释放将会触发异常[此模式不下允许以递归方式获取写入锁定]
                LogWriteLock.ExitWriteLock();
            }

        }

 

发表评论