winform开启线程实时输出日志到控件
1、声明委托
public delegate void ShowMessage2Form(string message);
2、声明事件
static public event ShowMessage2Form ShowMessage;
3、事件绑定
LogHelper.ShowMessage += ShowLog;
4、方法实现:实时显示到主窗口控件上
private void ShowLog(string message) { try { if (txtLog2Display.InvokeRequired) { txtLog2Display.BeginInvoke(new MethodInvoker(delegate { txtLog2Display.AppendText(message + "\r\n"); })); } else { txtLog2Display.AppendText(message + "\r\n"); } } catch (Exception error) { LogHelper.Log(NLog.LogLevel.Error, this.GetType().FullName, System.Reflection.MethodBase.GetCurrentMethod().Name, error.ToString()); } }
5、保存日志文件
第一种方法:采用第三方日志控件
NLogUtil.WriteFileLog(error_level, LogType.Form, function_name, log2write);
第二种方法:开启线程,将日志放置队列中,从队列中读取保存在文件中 不推荐,会阻塞主线程
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Concurrent; using System.IO; using System.Threading; /// <summary> /// 问题1:分类错误信号,并输出到界面控制台 /// </summary> namespace Sunny.Net.Log { public static class LogHelper { private static string log_path = ""; private static ConcurrentQueue<string> logdata = new ConcurrentQueue<string>(); private static Thread logthread; public delegate void ShowMessage2Form(string message); static public event ShowMessage2Form ShowMessage; static public event ShowMessage2Form ShowMessage2; static private StreamWriter logwriter; public static void StartLogSave() { string folderpath = string.Format("{0}{1}", System.Environment.CurrentDirectory, @"\Log");//组合得到文件存储路径 if (System.IO.Directory.Exists(folderpath) == false)//判断路径是否存在,若否,则创建 { Directory.CreateDirectory(folderpath); } log_path = string.Format("{0}{1}{2}{3}", folderpath, @"\", DateTime.Now.ToString("MM_dd_HH_mm"), ".txt");//创建LOG文件 logwriter = new StreamWriter(log_path, true); logthread = new Thread(SaveLogThread); logthread.Start(); } public static void StopLogSave() { while (!logdata.IsEmpty) continue; logthread.Abort(); logwriter.Close(); logwriter.Dispose(); } public static void Log(string error_level, string layer, string function_name, string log2write) { try { if (logthread == null) StartLogSave(); //else logthread.Resume(); //else if (logthread.ThreadState != ThreadState.Running) logthread.Start(); //if (logthread.ThreadState != ThreadState.Running) StartLogSave(); //DeBug模式,其他模式需根据error_level进行改变输出,界面输出与文件输出需隔开 string queuelog = string.Format("[{0}][{1}]::{2}.{3}:{4}", DateTime.Now.ToString("MM/dd HH:mm:ss:fff"), error_level, layer, function_name, log2write); logdata.Enqueue(queuelog); if (error_level == "INFO" && error_level != null) ShowMessage(string.Format("[{0}]:{1}:{2}", DateTime.Now.ToString("HH:mm:ss:fff"), function_name, log2write)); if (error_level == "INFO2" && error_level != null) ShowMessage2(string.Format("[{0}]:{1}:{2}", DateTime.Now.ToString("HH:mm:ss:fff"), function_name, log2write)); } catch (Exception e) { // MessageBox.Show("LOG写入队列失败:" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private static void SaveLogThread() { try { string logmessage = null; for (; ; ) { if (logdata.Count > 0) { logdata.TryDequeue(out logmessage); if (logmessage != null) logwriter.WriteLine(logmessage); logwriter.Flush(); } } } catch (Exception e) { throw e; // MessageBox.Show("LOG写入文件失败:" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }