Updated (6/17/2004 @ 8:46p): The constructor should be static, not private. :-)
On one of my projects, I didn't really want to use Log4Net and I certainly didn't want to log to the Event Log, so I looked into using a TraceListener. The solution detailed below works extremely well for me. The cool thing is that when I'm running the app in the IDE, not only is the file created (with being TRACE), I get the messages in the Output window.
Are there better solutions? Probably. I have to tell you that I tried to get Log4Net working with this project and I couldn't get past the configuration section of the docs.
Usage:
Log.Trace(“This is a test“);
Log.Info(“Informational message“);
Output will be a file named _MM_dd_yy.log. The layout of the file is:
hh:mm:ss AM|PMseveritymessage
I created a class named Log with several static methods (and a private constructor).
public class Log {
static Log() {
Trace.Listenders.Add(new TextWriterTraceListener(Configuration.LogDestination + GetDatedFilename(“log“)));
}
public static void Info(string message) {
writeToLog(message, 9);
}
public static void Status(string message) {
writeToLog(message, 5);
}
public static void Alert(string message) {
writeToLog(message, 3);
}
public static void CriticalAlert(string message) {
writeToLog(message, 1);
}
public static void writeToLog(string message, int severity) {
Trace.WriteLine(System.DateTime.Now.ToLongTimeString() + “\t“ + severity.ToString() + “\t“ + message);
Trace.Flush();
}
private static string GetBaseName() {
string[] tempPath = Environment.GetCommandLineArgs();
string temp = tempPath[tempPath.GetUpperBound(0)];
return Path.GetFileNameWithoutExtension(@temp);
}
private static string GetDatedFileName(string extension) {
string basename = GetBaseName();
string currentDate = DateTime.Now.ToString(“MM_dd_yy“);
return basename + “_“ + currentDate + “.“ + extension;
}
}