/// <summary> /// 写日志(可以多线程操作) /// </summary> /// <param name="info"></param> public void Write(LogInfo info) { // 日志过滤 if (info.MessageFlag < level) return; bool bIsLock = false; lock (s_LockLogInfoQueue) { s_LogInfoQueue.Enqueue(info); // 检测是否有其它的线程已在处理中,如在使用就退出,否则开始锁定 if (s_IsLock == false) bIsLock = s_IsLock = true; } // 如果有其它的线程在处理就退出 if (bIsLock == false) return; ThreadPool.QueueUserWorkItem((o) => { LogInfo[] logInfoArray; do { logInfoArray = null; lock (s_LockLogInfoQueue) { if (s_LogInfoQueue.Count > 0) { logInfoArray = s_LogInfoQueue.ToArray(); s_LogInfoQueue.Clear(); } else s_IsLock = false; // 没有数据需要处理,释放锁定让其它的程序来继续处理 } if (logInfoArray == null) break; for (int iIndex = 0; iIndex < logInfoArray.Length; iIndex++) { LogInfo logInfo = logInfoArray[iIndex]; if (logInfo.Parameter == null) InternalWriteLine(logInfo.MessageFlag, logInfo.Format); else InternalWriteLine(logInfo.MessageFlag, logInfo.Format, logInfo.Parameter); } } while (true); }); }
/// <summary> /// 日志输出 /// </summary> /// <param name="info"></param> public void Write(LogInfo info) { // 日志过滤 if (info.MessageFlag < level || info.MessageFlag > LogMessageType.MSG_FATALERROR) return; bool isLock = false; lock (s_lockLogFileInfoQueue) { logFileInfoQueue.Enqueue(info); // 检测是否有其它的线程已在处理中,如在使用就退出,否则开始锁定 if (isLockFile == false) isLock = isLockFile = true; } // 如果有其它的线程在处理就退出 if (isLock == false) return; LogInfo[] logInfoArray; do { logInfoArray = null; lock (s_lockLogFileInfoQueue) { if (logFileInfoQueue.Count > 0) { logInfoArray = logFileInfoQueue.ToArray(); logFileInfoQueue.Clear(); } else isLockFile = false; // 没有数据需要处理,释放锁定让其它的程序来继续处理 } if (logInfoArray == null) break; using (StreamWriter writer = File.AppendText(fileName)) { for (int iIndex = 0; iIndex < logInfoArray.Length; iIndex++) { LogInfo logInfo = logInfoArray[iIndex]; writer.WriteLine(logInfo.ToString()); } } } while (true); }