public class LoggerHelper { private static Queue<string> qMsg = null; private static string logFilePath = @"D:\log\"+ DateTime.Now.ToString("yyyy-MM-dd") + ".txt";//当然也可以改成读取配置文件 static LoggerHelper() { qMsg = new Queue<string>(); //存入日志 Run(); } public static void WriteLog(string strLog) { if (string.IsNullOrEmpty(strLog)) { return; } strLog = strLog.Replace("\n", "\r\n"); if (!File.Exists(logFilePath)) { File.Create(logFilePath).Dispose(); } using (StreamWriter sw = File.AppendText(logFilePath)) { sw.WriteLine("[" + DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss") + "] " + strLog); } } public static void Run() { ThreadPool.QueueUserWorkItem(a => { while (true) { string tmsg = string.Empty; lock (qMsg) { ) tmsg = qMsg.Dequeue(); } if (!String.IsNullOrEmpty(tmsg)) { WriteLog(tmsg); } ) { Thread.Sleep(); } } }); } public static void Run2() { Task.Run(() => { while (true) { string tmsg = string.Empty; lock (qMsg) { ) tmsg = qMsg.Dequeue(); } if (!String.IsNullOrEmpty(tmsg)) { WriteLog(tmsg); } ) { Thread.Sleep(); } } }); } public static void WriteLogAsync(string strlog) { lock (qMsg) { qMsg.Enqueue(strlog); } } public static void WriteLogAsync(string filepath, string strlog) { if (string.IsNullOrEmpty(filepath)) { WriteLogAsync(strlog); } else { logFilePath = filepath; lock (qMsg) { qMsg.Enqueue(strlog); } } } }
使用:
static void Main(string[] args) { string filepath=@"F:\log\"+ DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; Parallel.For(,,index=>{ string msg1 = "test" + index.ToString(); LoggerHelper.WriteLogAsync("", msg1); });
Console.ReadLine(); }