C# 日志记录工具类--LogHelper.cs测试


C# 日志记录工具类:(适用于不想使用log4j等第三方的Log工具的时候,希望自己写个简单类实现)
LogHelper.cs内容如下:
  1 using System;
  2 using System.Diagnostics;
  3 using System.IO;
  4 using System.Text;
  5 using System.Threading;
  6 using System.Collections.Generic;
  7 
  8 namespace Tools.Log
  9 {
 10     /// <summary>
 11     /// 多线程安全Log记录工具20180314
 12     /// </summary>
 13     public class LogHelper
 14     {
 15         //为了使用DBGView进行在线调试:
 16         //System.Diagnostics.Debug.WriteLine("Debug模式可见")
 17         //System.Diagnostics.Trace.WriteLine("Debug、Release都可见");
 18 
 19         private static  Thread WriteThread;
 20         private static readonly Queue<string> MsgQueue;
 21 
 22         private static readonly string FilePath;
 23 
 24         private static Boolean autoResetEventFlag = false;
 25         private static AutoResetEvent aEvent = new AutoResetEvent(false);
 26         private static bool flag = true;
 27         public static bool LogFlag = true;
 28 
 29         static LogHelper()
 30         {
 31             FilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "App_Log\\";
 32             WriteThread = new Thread(WriteMsg);
 33             MsgQueue = new Queue<string>();
 34             WriteThread.Start();
 35         }
 36 
 37         public static void LogInfo(string msg)
 38         {
 39             Monitor.Enter(MsgQueue);
 40             MsgQueue.Enqueue(string.Format("{0} {1} {2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"), "Info", msg));
 41             Monitor.Exit(MsgQueue);
 42             if (autoResetEventFlag) {
 43                 aEvent.Set();
 44             }
 45         }
 46         public static void LogError(string msg)
 47         {
 48             Monitor.Enter(MsgQueue);
 49             MsgQueue.Enqueue(string.Format("{0} {1} {2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"), "Error", msg));
 50             Monitor.Exit(MsgQueue);
 51             if (autoResetEventFlag)
 52             {
 53                 aEvent.Set();
 54             }
 55         }
 56         public static void LogWarn(string msg)
 57         {
 58             Monitor.Enter(MsgQueue);
 59             MsgQueue.Enqueue(string.Format("{0} {1} {2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"), "Warn", msg));
 60             Monitor.Exit(MsgQueue);
 61             if (autoResetEventFlag)
 62             {
 63                 aEvent.Set();
 64             }
 65         }
 66 
 67         /// <summary>
 68         /// ExitThread是退出日志记录线程的方法,一旦退出,无法开启,一般在程序关闭时执行
 69         /// </summary>
 70         public static void ExitThread() {
 71             flag = false;
 72             aEvent.Set();//恢复线程执行
 73         }
 74         private static void WriteMsg()
 75         {
 76             while (flag)
 77             {
 78                 //进行记录
 79                 if (LogFlag)
 80                 {
 81                     autoResetEventFlag = false;
 82                     if (!Directory.Exists(FilePath))
 83                     {
 84                         Directory.CreateDirectory(FilePath);
 85                     }
 86                     string fileName = FilePath + DateTime.Now.ToString("yyyy-MM-dd") + "-Dic.log";
 87                     var logStreamWriter = new StreamWriter(fileName, true);
 88                     while (MsgQueue.Count > 0)
 89                     {
 90                         Monitor.Enter(MsgQueue);
 91                         string msg = MsgQueue.Dequeue();
 92                         Monitor.Exit(MsgQueue);
 93                         logStreamWriter.WriteLine(msg);
 94                         if (GetFileSize(fileName) > 1024 * 5)
 95                         {
 96                             logStreamWriter.Flush();
 97                             logStreamWriter.Close();
 98                             CopyToBak(fileName);
 99                             logStreamWriter = new StreamWriter(fileName, false);
100                             logStreamWriter.Write("");
101                             logStreamWriter.Flush();
102                             logStreamWriter.Close();
103                             logStreamWriter = new StreamWriter(fileName, true);
104                         }
105                         //下面用于DbgView.exe工具进行在线调试
106                         System.Diagnostics.Debug.WriteLine("BS_Debug:"+msg);
107                         System.Diagnostics.Trace.WriteLine("BS_Release:" + msg);
108                     }
109                     logStreamWriter.Flush();
110                     logStreamWriter.Close();
111                     autoResetEventFlag = true;
112                     aEvent.WaitOne();
113                 }
114                 else {
115                     autoResetEventFlag = true;
116                     aEvent.WaitOne();
117                 }
118             }
119         }
120         private static long GetFileSize(string fileName)
121         {
122             long strRe = 0;
123             if (File.Exists(fileName))
124             {
125                 var myFs=new FileInfo(fileName);
126                 strRe = myFs.Length / 1024;
127                 //Console.WriteLine(strRe);
128             }
129             return strRe;
130         }
131         private static void CopyToBak(string sFileName)
132         {
133             int fileCount = 0;
134             string sBakName = "";
135             do
136             {
137                 fileCount++;
138                 sBakName = sFileName + "." + fileCount + ".BAK";
139             }
140             while (File.Exists(sBakName));
141             File.Copy(sFileName, sBakName);
142         }
143     }
144 }

 

该类由BS风华改编自网上一个类。实现了多线程下面安全记录日志的功能:

使用方法:

1    Tools.Log.LogHelper.LogFlag = true; //开启记录
2    Tools.Log.LogHelper.LogInfo("==========日志记录内容 Info====");     
3    Tools.Log.LogHelper.LogWarn("==========日志记录内容 Warn====");
4    Tools.Log.LogHelper.LogError("==========日志记录内容 Error====");
5    Tools.Log.LogHelper.LogFlag = false;//停止记录

Tools.Log.LogHelper.
ExitThread();// 退出日志记录线程,一般在程序退出时候调用。

如果有更好的方式,欢迎留言

posted @ 2018-03-21 14:37  柒月风华  阅读(5304)  评论(0编辑  收藏  举报