/// <summary> /// 日志处理帮助类 /// </summary> public class LogHelper { private static Queue<string> ErrorQueue = new Queue<string>(); static Action<string> errorAction; static string LogPath => System.Web.Hosting.HostingEnvironment.MapPath($"/App_Data/Log/{DateTime.Now.ToString("yyyyMMdd")}.txt"); static LogHelper() { errorAction += WriteFile; Task.Run(() => { while (true) { if (ErrorQueue.Count > 0) { lock (ErrorQueue) { var txt = ErrorQueue.Dequeue(); //出队列 errorAction?.Invoke(txt); //写日志 } } else { Task.Delay(100); } } }); } /// <summary> /// 讲内容写入日志队列中 /// </summary> /// <param name="errorText"></param> public static void WriteLog(string errorText) { lock (ErrorQueue) { ErrorQueue.Enqueue(errorText); //进队列 } } /// <summary> /// 写入文本文件 /// </summary> /// <param name="txt"></param> static void WriteFile(string txt) { using (System.IO.FileStream fs = new System.IO.FileStream(LogPath, System.IO.FileMode.Append, System.IO.FileAccess.Write)) { var byteStr = Encoding.Default.GetBytes(txt); fs.Write(byteStr, 0, byteStr.Length); } } }
Asp.Net Mvc日志处理帮助类