首页 > 代码库 > 日志log
日志log
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(); }
日志log
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。