寫網站程序的時候,都要把異常寫入日誌吧,比較經常使用的是Log4Net,不過我要求不高,只須要把異常和信息記在網站服務器的網站目錄下就能夠了,因而我本身寫了一個。服務器
public static class Logger { private static readonly object Obj = new object(); public static void Log(string title, string msg) { LogError(title, msg); } public static void Error(string title, Exception ex) { if (ex == null) { return; } var sb = new StringBuilder(); sb.AppendLine(ex.Message).AppendLine(ex.StackTrace); foreach (IDictionary value in ex.Data.Values) { if (value != null) { foreach (DictionaryEntry entry in value) { sb.Append("Key:").Append(entry.Key).Append(",Value:").AppendLine(entry.Value.ToString()); } } } if (ex.InnerException != null) { sb.Append("InnerMessage:") .AppendLine(ex.InnerException.Message) .Append("InnerStackTrace:") .AppendLine(ex.InnerException.StackTrace); foreach (IDictionary value in ex.InnerException.Data.Values) { if (value != null) { foreach (DictionaryEntry entry in value) { sb.Append("InnerKey:") .Append(entry.Key) .Append(",InnerValue:") .AppendLine(entry.Value.ToString()); } } } } LogError(title, sb.ToString()); } private static void LogError(string title, string msg) { string filePath = Path.GetDirectoryName(HttpRuntime.AppDomainAppPath) + "\\log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; lock (Obj) { try { File.AppendAllText(filePath, string.Format("{0:HH:mm:ss}:{1}:{2}\r\n", DateTime.Now, title, msg)); } catch (Exception e) { Console.WriteLine(e); } } } }
記錄普通訊息沒什麼難的,記錄異常的話就要選擇記錄哪些信息了,這裏我沒把Source,HelpLink和TargetSite記錄下來,由於我感受他們沒什麼用,這裏惟一難點的就是寫日誌加鎖,爲什麼要加鎖呢,由於同一文件同一時間只能被一個進行寫入呀,把日誌類搞成靜態類也是出於這個考慮的。網站