private void ThreadPoolSaveText(object obj) { // 进入文件操作的锁 m_fileSaveLock.Enter(); //获取要存储的文件名称 string LogSaveFileName = GetFileSaveName(); if (!string.IsNullOrEmpty(LogSaveFileName)) { // 保存 StreamWriter sw = null; try { sw = new StreamWriter(LogSaveFileName, true, Encoding.UTF8); string str = obj as string; sw.Write(str); } catch (Exception ex) { AddItemToCache(new CommonMessageItem() { Degree = CommonMessageDegree.FATAL, Text = LogNetManagment.GetSaveStringFromException("LogNetSelf", ex), }); } finally { sw?.Dispose(); } } // 释放锁 m_fileSaveLock.Leave(); }
private string CommonMessageFormate(CommonMessageItem CommonMessage) { StringBuilder stringBuilder = new StringBuilder(); if (CommonMessage.Degree != CommonMessageDegree.None) { stringBuilder.Append("\u0002"); stringBuilder.Append("["); stringBuilder.Append(LogNetManagment.GetDegreeDescription(CommonMessage.Degree)); stringBuilder.Append("] "); stringBuilder.Append(CommonMessage.Time.ToString("yyyy-MM-dd HH:mm:ss.fff")); stringBuilder.Append(" thread:["); stringBuilder.Append(CommonMessage.ThreadId.ToString("D2")); stringBuilder.Append("] "); if (!string.IsNullOrEmpty(CommonMessage.KeyWord)) { stringBuilder.Append(CommonMessage.KeyWord); stringBuilder.Append(" : "); } } stringBuilder.Append(CommonMessage.Text); return(stringBuilder.ToString()); }
private void ThreadPoolSaveFile(object obj) { // 获取需要存储的日志 CommonMessageItem current = GetAndRemoveLogItem(); // 进入文件操作的锁 m_fileSaveLock.Enter(); // 获取要存储的文件名称 string LogSaveFileName = GetFileSaveName(); if (!string.IsNullOrEmpty(LogSaveFileName)) { // 保存 StreamWriter sw = null; try { sw = new StreamWriter(LogSaveFileName, true, Encoding.UTF8); while (current != null) { // 触发事件 OnBeforeSaveToFile(new CommonEventArgs() { CommonMessage = current }); // 检查是否需要真的进行存储 bool isSave = true; filtrateLock.Enter(); isSave = !filtrateKeyword.Contains(current.KeyWord); filtrateLock.Leave(); // 检查是否被设置为强制不存储 if (current.Cancel) { isSave = false; } // 如果需要存储的就过滤掉 if (isSave) { sw.Write(CommonMessageFormate(current)); sw.Write(Environment.NewLine); } current = GetAndRemoveLogItem(); } } catch (Exception ex) { AddItemToCache(current); AddItemToCache(new CommonMessageItem() { Degree = CommonMessageDegree.FATAL, Text = LogNetManagment.GetSaveStringFromException("LogNetSelf", ex), }); } finally { sw?.Dispose(); } } // 释放锁 m_fileSaveLock.Leave(); Interlocked.Exchange(ref m_SaveStatus, 0); // 再次检测锁是否释放完成 if (m_WaitForSave.Count > 0) { StartSaveFile(); } }
/// <summary> /// 写入一条异常信息 /// </summary> /// <param name="keyWord">关键字</param> /// <param name="text">内容</param> /// <param name="ex">异常</param> public void WriteException(string keyWord, string text, Exception ex) { RecordMessage(CommonMessageDegree.FATAL, keyWord, LogNetManagment.GetSaveStringFromException(text, ex)); }