标签:style blog class code c java
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.IO; 5 using System.Diagnostics; 6 7 namespace UtilityClass 8 { 9 public class TraceLog : TraceListener 10 { 11 // 初始化时给定一个日志文件位置 12 private string filePath; 13 14 public TraceLog() 15 : this("") 16 { } 17 18 public TraceLog(string filepath) 19 { 20 if (filepath.IndexOfAny(Path.GetInvalidFileNameChars()) > -1) 21 { 22 ShowMsg.ShowErr(null, "指定路径无效!\r\n\r\n请重新设置日志文件路径!"); 23 Trace.Listeners.Clear(); 24 return; 25 } 26 filePath = ConvertX.IsNullOrEmpty(filepath) ? AppDomain.CurrentDomain.BaseDirectory + "\\Error.Log" : Path.GetFullPath(filepath); 27 } 28 29 /// <summary> 30 /// 保存 错误信息 到指定日志 31 /// 此方法已重写 实际效果同 WriteLine 32 /// </summary> 33 public override void Write(string message) 34 { 35 File.AppendAllText(filePath, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine + message + Environment.NewLine); 36 } 37 38 /// <summary> 39 /// 保存 错误信息 到指定日志 40 /// </summary> 41 public override void WriteLine(string message) 42 { 43 File.AppendAllText(filePath, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine + message + Environment.NewLine); 44 } 45 46 /// <summary> 47 /// 输入一个 Exception 对象 48 /// 它将在日志文件中保存 错误信息 和 堆栈信息 49 /// </summary> 50 public override void WriteLine(object o) 51 { 52 string msg = ""; 53 Exception ex = o as Exception; 54 if (ex != null) 55 { 56 msg = ex.Message + Environment.NewLine; 57 msg += ex.StackTrace; 58 } 59 else if (o != null) 60 { 61 msg = o.ToString(); 62 } 63 WriteLine(msg); 64 } 65 66 /// <summary> 67 /// 输入一个 错误信息 和一个 分类名称 68 /// 它将在日志文件中保存 错误信息 69 /// </summary> 70 public override void WriteLine(string message, string category) 71 { 72 string msg = ""; 73 if (!ConvertX.IsNullOrEmpty(category)) 74 { 75 msg = category + ":"; 76 } 77 msg += message; 78 WriteLine(msg); 79 } 80 81 /// <summary> 82 /// 输入一个 Exception 对象和一个 分类名称 83 /// 它将在日志文件中保存 错误信息 和 堆栈信息 84 /// </summary> 85 public override void WriteLine(object o, string category) 86 { 87 string msg = ""; 88 if (!ConvertX.IsNullOrEmpty(category)) 89 { 90 msg = category + ":"; 91 } 92 if (o is Exception) 93 { 94 var ex = (Exception)o; 95 msg += ex.Message + Environment.NewLine; 96 msg += ex.StackTrace; 97 } 98 else if (o != null) 99 { 100 msg = o.ToString(); 101 } 102 WriteLine(msg); 103 } 104 } 105 }
TraceLog.cs 累积 C#,布布扣,bubuko.com
标签:style blog class code c java
原文地址:http://www.cnblogs.com/z5337/p/3725017.html