Пример #1
0
 /// <summary>
 /// 向队列添加错误
 /// </summary>
 /// <param name="logModel"></param>
 public static void AddLogQueue(LogQueueModel logModel)
 {
     lock (LogLock) //入队防止并发 这个对象貌似不是线程安全
     {
         LogQueue.Enqueue(logModel);
     }
 }
Пример #2
0
        /// <summary>
        /// 异步日志 处理 解决lock锁 阻塞线程
        /// </summary>
        public static void WriteLog()
        {
            #region 测试错误
            //AddLogQueue(new LogQueueModel()
            //{
            //    Msg = "测试错误",
            //    FileName = "ApiError"
            //});
            #endregion

            ThreadPool.QueueUserWorkItem(s =>
            {
                while (true)
                {
                    if (LogQueue.Count > 0)
                    {
                        //从队列里去读取信息
                        LogQueueModel contentTxt = LogQueue.Dequeue();
                        string upLoadPath        = $"{ AppDomain.CurrentDomain.BaseDirectory}/{contentTxt.FileName}/";
                        upLoadPath += DateTime.Now.ToString("yyyy") + '/';
                        upLoadPath += DateTime.Now.ToString("MM") + '/';
                        if (!System.IO.Directory.Exists(upLoadPath))
                        {
                            System.IO.Directory.CreateDirectory(upLoadPath);
                        }
                        StringBuilder content = new StringBuilder();
                        content.Append("\r\n" + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
                        content.Append("\r\n\t content:" + contentTxt.Msg);
                        content.Append("\r\n\t 本条记录由 日志队列 处理线程产生");
                        content.Append("\r\n--------------------------------------------------------------------------------------------------");
                        System.IO.File.AppendAllText(upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + ".log", content.ToString(), System.Text.Encoding.UTF8);
                    }
                    Thread.Sleep(5000);//5秒读一次
                }
            });
        }