private void AddItemToCache(HslMessageItem item) { m_simpleHybirdLock.Enter(); m_WaitForSave.Enqueue(item); m_simpleHybirdLock.Leave(); StartSaveFile(); }
private void WriteToFile(HslMessageDegree degree, string keyWord, string text) { // 过滤事件 if (degree <= m_messageDegree) { // 需要记录数据 HslMessageItem item = GetHslMessageItem(degree, keyWord, text); AddItemToCache(item); } }
private HslMessageItem GetAndRemoveLogItem() { HslMessageItem result = null; m_simpleHybirdLock.Enter(); result = m_WaitForSave.Count > 0 ? m_WaitForSave.Dequeue() : null; m_simpleHybirdLock.Leave(); return(result); }
private string HslMessageFormate(HslMessageItem hslMessage) { StringBuilder stringBuilder = new StringBuilder("\u0002"); stringBuilder.Append("["); stringBuilder.Append(LogNetManagment.GetDegreeDescription(hslMessage.Degree)); stringBuilder.Append("] "); stringBuilder.Append(hslMessage.Time.ToString("yyyy-MM-dd HH:mm:ss.fff")); stringBuilder.Append(" thread:["); stringBuilder.Append(hslMessage.ThreadId.ToString("D2")); stringBuilder.Append("] "); if (!string.IsNullOrEmpty(hslMessage.KeyWord)) { stringBuilder.Append(hslMessage.KeyWord); stringBuilder.Append(" : "); } stringBuilder.Append(hslMessage.Text); return(stringBuilder.ToString()); }
private void ThreadPoolSaveFile(object obj) { // 获取需要存储的日志 HslMessageItem 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 HslEventArgs( ) { HslMessage = current }); // 检查是否需要真的进行存储 bool isSave = true; filtrateLock.Enter( ); isSave = !filtrateKeyword.Contains(current.KeyWord); filtrateLock.Leave( ); // 检查是否被设置为强制不存储 if (current.Cancel) { isSave = false; } // 如果需要存储的就过滤掉 if (isSave) { sw.Write(HslMessageFormate(current)); sw.Write(Environment.NewLine); } current = GetAndRemoveLogItem(); } } catch (Exception ex) { AddItemToCache(current); AddItemToCache(new HslMessageItem() { Degree = HslMessageDegree.FATAL, Text = LogNetManagment.GetSaveStringFromException("LogNetSelf", ex), }); } finally { sw?.Dispose(); } } // 释放锁 m_fileSaveLock.Leave(); Interlocked.Exchange(ref m_SaveStatus, 0); // 再次检测锁是否释放完成 if (m_WaitForSave.Count > 0) { StartSaveFile(); } }