Self-made mini logs and self-made logs
When writing website programs, you must write exceptions to logs. Log4Net is commonly used, but I do not have high requirements, you only need to record the exceptions and information in the website directory of the website server, so I wrote one by myself.
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); } } } }
There is no difficulty in recording common information. If an exception is recorded, you should choose which information to record. Here I did not record Source, HelpLink, and TargetSite, because I feel they are useless, the only difficulty here is to lock the log writing. Why should we lock it? Because only one file can be written at the same time, and it is also out of this consideration to convert the log class into a static class.