.Net 之自定义Log

话不多说,以下是简单的一个logHelper类和一个小demo

1.LogDto:主要封装一些记录日志用到的东西,比如日志信息和日志类型等等

public class LogDto
{
  public string message { get; set; }
   public LogType LogType { get; set; }
}

2.LogHelper:日志帮助类

1)定义一个队列,当调用WriteLog方法时就把要记录的实体入队

2)定义一个委托,写日志的话可能会有多种形式,可以是写在文本也可以是写在数据库等.那么又可以定义方法WriteToTxt,WriteToDataBase等;

3)静态构造函数.开启一个线程监测队列里面是否有数据,这里就相当于观察者模式.当有数据的时候,观察者就需要做出对应的动作(WriteToTxt,WriteToDataBase)这里为了方便写在一个类里面,偷个懒吧。所以就又得先让他们和委托关联起来,当有数据的时候,让日志对象出列并调用委托就OK了

    public class LogHelper
      {

       public static Queue<LogDto> queueList = new Queue<LogDto>()
            private static Action<LogDto> QueueAction;
            public static void WriteLog(LogDto logDto)
            {
                  lock (queueList)
                  {
                        queueList.Enqueue(logDto);
                  }
            }

            static LogHelper()
            {
                  QueueAction = WriteToTxt;
                  QueueAction += WriteToDataBase;
                 //开启线程
                  Task.Run(() =>
                  {
                        while (true)
                        {
                              if (queueList.Any())
                              {
                                 var logdto = queueList.Dequeue();
                                 QueueAction.Invoke(logdto);
                            }
                              else
                                    Thread.Sleep(500);
                        }
                  });
            }

            private static void WriteToTxt(LogDto logDto)
            {
               var path = Path.Combine(Directory.GetCurrentDirectory(), "log.txt");
               StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8);
               sw.WriteLine($"------------------------ Log Begin-------------------------------------------------------------------");
               sw.WriteLine($" 1) Happened Time:{DateTime.Now}");
               sw.WriteLine($" 2) Log Type:{logDto.LogType}");
               sw.WriteLine($" 3) Context:{logDto.message}");
               sw.WriteLine($"----------------------------------------------Log End-------------------------------------------------");
               sw.WriteLine();
               sw.Close();
          }
            private static void WriteToDataBase(LogDto logDto)
            {
                  //..
            }
      }

3.Demo:一个简单的WinForm,模拟写日志的场景,这里就不贴代码了

4.执行结果

 

猜你喜欢

转载自www.cnblogs.com/berlinman/p/12079547.html