I wrote up a very simple C# class that provides logging for C# applications since the C# Logger on sourceforge is still in alpha (and doesn’t appear to be active) and the .NET framework doesn’t seem to provide normal text file logging outside of the EventLog (correct me if I’m wrong):
using System;
using System.IO;
namespace com.ignitionlabs.logging {
public class Logger {
private static int _ALL = 100;
private static int _INFO = 75;
private static int _ERROR = 50;
private static int _OFF = 0;
private static String logDirectory = System.Configuration.ConfigurationSettings.AppSettings["logging.directory"].ToString();
public static int ALL {
get { return _ALL; }
}
public static int ERROR {
get { return _ERROR; }
}
public static int INFO {
get { return _INFO; }
}
public static int OFF {
get { return _OFF; }
}
public static void append(String message, int level) {
int logLevel = _OFF;
String strLogLevel = System.Configuration.ConfigurationSettings.AppSettings["logging.level"].ToString();
switch(strLogLevel) {
case "ALL":
logLevel = _ALL;
break;
case "ERROR":
logLevel = _ERROR;
break;
case "INFO":
logLevel = _INFO;
break;
default:
logLevel = _OFF;
break;
}
if (logLevel >= level) {
DateTime dt = DateTime.Now;
String filePath = logDirectory + dt.ToString("yyyyMMdd") + ".log";
if (!File.Exists(filePath)) {
FileStream fs = File.Create(filePath);
fs.Close();
}
try {
StreamWriter sw = File.AppendText(filePath);
sw.WriteLine(dt.ToString("hh:mm:ss") + "|" + message);
sw.Flush();
sw.Close();
} catch (Exception e) {
Console.WriteLine(e.Message.ToString());
}
}
}
}
}
After compiling, you’ll need to add 2 elements to your <appsettings> in web.config:
<add key=”logDirectory” value=”c:\myapp\logs\” />
<add key=”logLevel” value=”ALL|INFO|ERROR|OFF” />
and then you can use the class like this:
Logger.append(“your application message…”, Logger.ALL);
As always, I’m interested in any design flaws or critiques.