日志工具类_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 日志工具类

日志工具类

 2013/11/27 17:28:06  Mr吕  博客园  我要评论(0)
  • 摘要:分享一个自己写的日志工具类1usingSystem;2usingSystem.Collections.Generic;3usingSystem.Text;4usingSystem.IO;5usingSystem.Diagnostics;67namespaceLIC.Common8{9///<summary>10///日志级别枚举11///</summary>12publicenumLogLevels13{14///<summary>
  • 标签:工具

分享一个自己写的日志工具类

 

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Text;
  4 using System.IO;
  5 using System.Diagnostics;
  6 
  7 namespace LIC.Common
  8 {
  9     /// <summary>
 10     /// 日志级别枚举
 11     /// </summary>
 12     public enum LogLevels
 13     { 
 14         /// <summary>
 15         /// 16         /// </summary>
 17         None, 
 18         /// <summary>
 19         /// 致命错误
 20         /// </summary>
 21         Fatal,
 22         /// <summary>
 23         /// 普通错误
 24         /// </summary>
 25         Error,
 26         /// <summary>
 27         /// 警告信息
 28         /// </summary>
 29         Warn,
 30         /// <summary>
 31         /// 正常信息
 32         /// </summary>
 33         Info, 
 34         /// <summary>
 35         /// 调试信息
 36         /// </summary>
 37         Debug 
 38     }
 39 
 40     /// <summary>
 41     /// 日志打印类
 42     /// </summary>
 43     public class Log
 44     {
 45         private static object LockObj = new object();
 46 
 47         private static Encoding _LogEncoding = Encoding.UTF8;
 48         public static Encoding LogEncoding
 49         {
 50             get { return _LogEncoding; }
 51             set { _LogEncoding = value; }
 52         }
 53 
 54         private static LogLevels _Level = LogLevels.Debug;
 55         /// <summary>
 56         /// 日志显示级别 显示低于或等于该级别的日志
 57         /// </summary>
 58         public static LogLevels Level
 59         {
 60             get { return _Level; }
 61             set
 62             {
 63                 _Level = value;
 64             }
 65         }
 66 
 67         private static string _LogFolder = Environment.CurrentDirectory + "\\Log";
 68         /// <summary>
 69         /// 日志存放目录
 70         /// </summary>
 71         public static string LogFolder
 72         {
 73             get { return _LogFolder; }
 74             set
 75             {
 76                 _LogFolder = value;
 77             }
 78         }
 79 
 80         private static bool _IncldDateFldr = false;
 81         /// <summary>
 82         /// 日志是否按产生日期存放在不同的目录中
 83         /// </summary>
 84         public static bool IncldDateFldr
 85         {
 86             get { return _IncldDateFldr; }
 87             set 
 88             {
 89                 _IncldDateFldr = value;
 90             }
 91         }
 92 
 93         private static bool _IncldDateName = true;
 94         /// <summary>
 95         /// 日志名称中是否包含日期
 96         /// </summary>
 97         public static bool IncldDateName
 98         {
 99             get { return _IncldDateName; }
100             set
101             {
102                 _IncldDateName = value;
103             }
104         }
105 
106         private static string _LogName = Process.GetCurrentProcess().ProcessName;
107         /// <summary>
108         /// 日志名称
109         /// </summary>
110         public static string LogName
111         {
112             get { return _LogName; }
113             set
114             {
115                 _LogName = value;
116             }
117         }
118 
119 
120         private static string _LogFile = null;
121         /// <summary>
122         /// 日志路径
123         /// </summary>
124         public static string LogFile
125         {
126             get
127             {
128                 if (_LogFile == null)
129                 {
130                     StringBuilder sb = new StringBuilder();
131 
132                     sb.Append(LogFolder);
133                     sb.Append("\\");
134                     if (IncldDateFldr)
135                     {
136                         sb.Append(ToSimpleDate(DateTime.Now));
137                     }
138 
139                     if (!Directory.Exists(sb.ToString()))
140                     {
141                         Directory.CreateDirectory(sb.ToString());
142                     }
143 
144                     sb.Append("\\");
145                     sb.Append(LogName);
146                     if (IncldDateName)
147                     {
148                         sb.Append("_");
149                         sb.Append(ToSimpleDate(DateTime.Now));
150                     }
151 
152                     sb.Append(".log");
153 
154                     return sb.ToString();
155                 }
156                 else
157                 {
158                     return _LogFile;
159                 }
160             }
161         }
162 
163         /// <summary>
164         /// 重置日志路径
165         /// </summary>
166         /// <param name="file">null为默认路径</param>
167         public static void ResetLogFile(string file)
168         {
169             _LogFile = file;
170         }
171 
172         /// <summary>
173         /// 获取项目代码的调用者信息
174         /// </summary>
175         /// <param name="offset">相对于GetUsrStackFrame的调用者偏移量 1GetUsrStackFrame 2我是谁 3谁调用了我</param>
176         /// <returns></returns>
177         private static StackFrame GetUsrStackFrame(int offset)
178         {
179             StackTrace st = new StackTrace(true);
180             StackFrame[] sfs = st.GetFrames();
181             StackFrame sf = null;
182             int idx = 0;
183             for (int i = 0; i < sfs.Length; i++)
184             {
185                 if (sfs[i].GetFileColumnNumber() == 0)//非项目代码的调用
186                     continue;
187 
188                 if (offset == idx++)
189                 {
190                     sf = sfs[i];
191                     break;
192                 }
193             }
194             if (sf == null)
195             {
196                 sf = new StackFrame("Null StackFrame", 0, 0);
197             }
198             return sf;
199         }
200         /// <summary>
201         /// 我是谁。。。返回调用者的代码位置信息
202         /// </summary>
203         /// <returns>返回调用者的代码位置信息</returns>
204         private static StackFrame WhoAmI()
205         {
206             return GetUsrStackFrame(2);
207         }
208 
209         /// <summary>
210         /// 谁调用了我?返回此次调用者的调用者信息
211         /// </summary>
212         /// <returns>返回此次调用者的调用者信息</returns>
213         private static StackFrame WhoCalledMe()
214         {
215             return GetUsrStackFrame(3);
216         }
217 
218         /// <summary>
219         /// 获取路径中的文件名220         /// </summary>
221         /// <param name="file">路径字符串</param>
222         /// <param name="includeSuffix">返回值中是否包含后缀名</param>
223         /// <returns>文件名</returns>
224         private static string BaseName(string file, bool includeSuffix)
225         {
226             int idx = -1;
227 
228             idx = file.LastIndexOf('\\');
229             if (idx >= 0)
230                 file = file.Substring(idx + 1);
231             if (!includeSuffix)
232             {
233                 idx = file.LastIndexOf('.');
234                 if (idx >= 0)
235                     file = file.Substring(0, idx);
236             }
237 
238             return file;
239         }
240 
241         /// <summary>
242         /// 转换成普通日期字符串
243         /// </summary>
244         /// <param name="value">公历日期</param>
245         /// <returns></returns>
246         private static string ToSimpleDate(DateTime value)
247         {
248             return value.ToString("yyyyMMdd");
249         }
250 
251         /// <summary>
252         /// 写日志
253         /// </summary>
254         /// <param name="cls">类名</param>
255         /// <param name="line">行数</param>
256         /// <param name="lvl">日志级别</param>
257         /// <param name="info">日志信息</param>
258         private static void WriteLog(string cls, int line, LogLevels lvl, string info)
259         {
260             lock (LockObj)
261             {
262                 try
263                 {
264                     StreamWriter swLog = new StreamWriter(LogFile, true, LogEncoding);
265 
266                     string[] ss = info.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
267                     if (ss.Length == 0)
268                         ss = new string[1];
269 
270                     swLog.WriteLine("[{0,-10}][{1,20}][{2,4:d4}][{3,6}]{4}",
271                         DateTime.Now.ToString("HHmmss:fff"), BaseName(cls, true), line, lvl.ToString(), ss[0]);
272 
273                     for (int i = 1; i < ss.Length; i++)
274                         swLog.WriteLine(ss[i]);
275 
276                     swLog.Flush();
277                     swLog.Close();
278                     swLog.Dispose();
279                 }
280                 catch (Exception) { }
281             }
282         }
283         /// <summary>
284         /// 格式由用户控制的写日志
285         /// </summary>
286         /// <param name="info"></param>
287         private static void WriteLogUser(string info)
288         {
289             lock (LockObj)
290             {
291                 try
292                 {
293                     StreamWriter swLog = new StreamWriter(LogFile, true, LogEncoding);
294 
295                     swLog.Write(info);
296 
297                     swLog.Flush();
298                     swLog.Close();
299                     swLog.Dispose();
300                 }
301                 catch (Exception) { }
302             }
303         }
304 
305         /// <summary>
306         /// 写入空行
307         /// </summary>
308         /// <param name="info"></param>
309         private static void WriteLogLine()
310         {
311             lock (LockObj)
312             {
313                 try
314                 {
315                     StreamWriter swLog = new StreamWriter(LogFile, true, LogEncoding);
316 
317                     swLog.WriteLine();
318 
319                     swLog.Flush();
320                     swLog.Close();
321                     swLog.Dispose();
322                 }
323                 catch (Exception) { }
324             }
325         }
326 
327         /// <summary>
328         /// 写日志
329         /// </summary>
330         /// <param name="lvl"></param>
331         /// <param name="inf"></param>
332         public static void Write(LogLevels lvl, string inf)
333         {
334             if (lvl > Level)
335                 return;
336             StackFrame sf = WhoCalledMe();
337             WriteLog(sf.GetFileName(), sf.GetFileLineNumber(), lvl, inf);
338         }
339 
340         /// <summary>
341         /// 格式由用户控制的写日志
342         /// </summary>
343         /// <param name="lvl"></param>
344         /// <param name="inf"></param>
345         public static void WriteUser(LogLevels lvl, string inf)
346         {
347             if (lvl > Level)
348                 return;
349             WriteLogUser(inf);
350         }
351 
352         /// <summary>
353         /// 写入空行
354         /// </summary>
355         /// <param name="lvl"></param>
356         public static void WriteLine(LogLevels lvl)
357         {
358             if (lvl > Level)
359                 return;
360             WriteLogLine();
361         }
362 
363         /// <summary>
364         /// 写致命错误
365         /// </summary>
366         /// <param name="inf"></param>
367         public static void Fatal(string inf)
368         {
369             if (LogLevels.Fatal > Level)
370                 return;
371             StackFrame sf = WhoCalledMe();
372             WriteLog(sf.GetFileName(), sf.GetFileLineNumber(), LogLevels.Fatal, inf);
373         }
374         /// <summary>
375         /// 写错误错误
376         /// </summary>
377         /// <param name="inf"></param>
378         public static void Error(string inf)
379         {
380             if (LogLevels.Error > Level)
381                 return;
382             StackFrame sf = WhoCalledMe();
383             WriteLog(sf.GetFileName(), sf.GetFileLineNumber(), LogLevels.Error, inf);
384         }
385         /// <summary>
386         /// 写普通信息
387         /// </summary>
388         /// <param name="inf"></param>
389         public static void Info(string inf)
390         {
391             if (LogLevels.Info > Level)
392                 return;
393             StackFrame sf = WhoCalledMe();
394             WriteLog(sf.GetFileName(), sf.GetFileLineNumber(), LogLevels.Info, inf);
395         }
396         /// <summary>
397         /// 写警告信息
398         /// </summary>
399         /// <param name="inf"></param>
400         public static void Warn(string inf)
401         {
402             if (LogLevels.Warn > Level)
403                 return;
404             StackFrame sf = WhoCalledMe();
405             WriteLog(sf.GetFileName(), sf.GetFileLineNumber(), LogLevels.Warn, inf);
406         }
407         /// <summary>
408         /// 写调试信息
409         /// </summary>
410         /// <param name="inf"></param>
411         public static void Debug(string inf)
412         {
413             if (LogLevels.Debug > Level)
414                 return;
415             StackFrame sf = WhoCalledMe();
416             WriteLog(sf.GetFileName(), sf.GetFileLineNumber(), LogLevels.Debug, inf);
417         }
418         /// <summary>
419         /// 设置打印级别
420         /// </summary>
421         /// <param name="level"></param>
422         public static void SetLevel(string level)
423         {
424             level = level.ToUpper();
425             switch (level)
426             {
427                 case "DEBUG":
428                 case "5":
429                     Level = LogLevels.Debug;
430                     break;
431                 case "INFO":
432                 case "INF":
433                 case "4":
434                     Level = LogLevels.Info;
435                     break;
436                 case "WARNING":
437                 case "WARN":
438                 case "3":
439                     Level = LogLevels.Warn;
440                     break;
441                 case "ERROR":
442                 case "ERR":
443                 case "2":
444                     Level = LogLevels.Error;
445                     break;
446                 case "FATAL":
447                 case "1":
448                     Level = LogLevels.Fatal;
449                     break;
450                 default:
451                     Level = LogLevels.None;
452                     break;
453             }
454         }
455         /// <summary>
456         /// 设置打印级别
457         /// </summary>
458         /// <param name="level"></param>
459         public static void SetLevel(int level)
460         {
461             SetLevel(level.ToString());
462         }
463     }
464 }
上一篇: WPF数据绑定Binding(二) 下一篇: 没有下一篇了!
发表评论
用户名: 匿名