ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

winform开启线程实时输出日志到控件

2022-08-18 09:33:38  阅读:140  来源: 互联网

标签:控件 string level static error 线程 logthread public 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);

第二种方法:开启线程,将日志放置队列中,从队列中读取保存在文件中 不推荐,会阻塞主线程

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);
            }
        }
    }
}
View Code

 

标签:控件,string,level,static,error,线程,logthread,public,winform
来源: https://www.cnblogs.com/1228941830ying/p/16580640.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有