标签:ring log color sync logfile logger create readline queue
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) { if (qMsg.Count > 0) tmsg = qMsg.Dequeue(); } if (!String.IsNullOrEmpty(tmsg)) { WriteLog(tmsg); } if (qMsg.Count <= 0) { Thread.Sleep(1000); } } }); } public static void Run2() { Task.Run(() => { while (true) { string tmsg = string.Empty; lock (qMsg) { if (qMsg.Count > 0) tmsg = qMsg.Dequeue(); } if (!String.IsNullOrEmpty(tmsg)) { WriteLog(tmsg); } if (qMsg.Count <= 0) { Thread.Sleep(1000); } } }); } 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(0,999,index=>{ string msg1 = "test" + index.ToString(); LoggerHelper.WriteLogAsync("", msg1); });
Console.ReadLine(); }
标签:ring log color sync logfile logger create readline queue
原文地址:http://www.cnblogs.com/cnft/p/6178788.html