C# - Class for logging

Post date: Feb 15, 2010 2:43:45 PM

public static class Logger { private static string fileName = System.Configuration.ConfigurationManager.AppSettings["LogFile"]; private static LogLevel logLevel = (LogLevel)Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["LogLevel"]); static string logHeaderFormat = "{0}\t\t{1}"; static string logMessageFormat = "\t\t\t{0}"; public static void Write(string message, LogLevel showMessageOnlyIfLevel) { if ((int)logLevel > 0) { StringBuilder sb = new StringBuilder(); string date = DateTime.Now.ToString(); sb.AppendLine(string.Format(logHeaderFormat, date, "")); if ((int)logLevel >= (int)LogLevel.Verbose && (int)showMessageOnlyIfLevel >= (int)LogLevel.Verbose) { StackTrace stackTrace = new StackTrace(true); // get call stack StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames) sb.AppendLine(string.Format(logHeaderFormat, "", "CallStack:")); // write call stack method names for (int i = 1; i < stackFrames.Length - 6; i++) { StackFrame stackFrame = stackFrames[i]; System.Reflection.MethodBase mb = stackFrame.GetMethod(); string classname = string.Format(logMessageFormat, mb.ReflectedType.Name); sb.AppendLine(string.Format("{0}.{1}() at line {2}, Column {3}", classname, mb.Name, stackFrame.GetFileLineNumber(), stackFrame.GetFileColumnNumber())); // write Class name } } if ((int)showMessageOnlyIfLevel > (int)logLevel) { return; } using (StreamWriter sw = File.AppendText(fileName)) { sb.AppendLine(string.Format(logHeaderFormat, "", "Message:")); sb.AppendLine(string.Format(logMessageFormat, message)); sw.Write(sb.ToString()); } } } public static void Write(string message) { Write(message, LogLevel.Message); } } public enum LogLevel { Message = 1, Verbose = 2, All = 3 }