自定义日志记录系统 UWP

自定义日志系统 UWP

  • 背景
    • 代码
    • 总结

背景

之前做了一个UWP的软件,和驱动要进行RPC通信。为了记录用户的操作以及方便定位是驱动的问题还是UWP的问题。我原本的单纯的使用写文件功能容易出现文件占用然后日志记录不全的问题,后面想了一下多线程的消费者生产者模式,有点类似这种模式写的日志,在0.1s写N多的情况下,没有漏记,没有崩溃,下面是代码

代码

public class WriteThread
    {
       static Queue<string> logStrQue = new Queue<string>();

        public static void addString(string str) {
            lock (logStrQue)
            {
                logStrQue.Enqueue(str);
            }
        }
        public static void createWriteThread() {
            //Task使用程序池创建线程,默认为后台线程
            Task writeTask = new Task(delegate()
            {
                while (true)
                {
                    while (logStrQue.Count > 0)
                    {
                        IEnumerable<string> list;
                        lock (logStrQue)
                        {
                            list =  logStrQue.AsEnumerable().ToArray();
                            FileUtil.writeToLogFile(list);
                            logStrQue.Clear();
                        }
                        Thread.Sleep(500);
                    }
                }
            });
            writeTask.Start();   
        }




    }

用了一个队列来保存UI线程加入的日志条目,然后死循环读取logStrQue,如果有增删改的操作记得加上锁,免得出现数据不对的情况。真正写的操作在FileUtil里面,我这边也把代码提供:

		[Windows.Foundation.Metadata.Overload("AppendTextAsync")]
        [Windows.Foundation.Metadata.RemoteAsync]
        public async static Task writeToLogFile(IEnumerable<string> list)
        {
            try
            {
                    StorageFile storageFile = await folder.CreateFileAsync(LogFileName, CreationCollisionOption.OpenIfExists);
                    if (storageFile == null)
                    {
                        storageFile = await folder.CreateFileAsync(LogFileName, CreationCollisionOption.ReplaceExisting);

                    }
                Debug.WriteLine(list.Count()+" : "+list.ToString());
                Windows.Storage.FileIO.AppendLinesAsync(storageFile, list).Close();
                //Windows.Storage.FileIO.AppendTextAsync(storageFile, str+ "\n").Close(); ;
                

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
          



        }

总结

其实这个功能非常的简单,没什么技术含量,但是由于之前我做的是安卓或者java后台,log的框架都很全,UWP属于新接触的,对框架没什么了解,所以自定义一个,感觉还是蛮有意思,比纯业务有意思。

你可能感兴趣的:(Winform,C#,多线程)