There's just enough here that I'd like to be able to come back and not once again reinvent the wheel. The locking in particular is something I often overlook when I re-roll app logging. I made a couple of edits from my "real" code to this generic code, so I'll have to test and come back if there are issues.

private static object _LogLock = 0;     // needs to be at the containing object's level
// so, in this case, static object global

// Convenience function to log jive.
public static void logStuff(string strToLog)
{
// obviously C:\temp must exist
string strLogFile = "C:\\temp\\appLog.log";
string strDateFormat = "MM/dd/yyyy hh:mm:ss.fff tt";

try
{
// When you have multiple AJAX (because, duh, asynchronous)
// calls going at once which, each of which might be calling
// parts of your .NET website that log stuff, you're likely to
// eventually run into concurrent logStuff calls. And since
// one "logStuff" might have your log file locked when the
// second comes along and also wants to log some stuff, you're
// going to want to lock the process so that you don't throw
// exceptions. Now, the second logStuff call will wait
// patiently until the lock on _LogLock is released.

// More information here:
// http://stackoverflow.com/questions/7419172/streamwriter-lock-not-working
// http://msdn.microsoft.com/en-us/library/c5kehkcz(v=vs.71).aspx
lock (_LogLock)
{
if (!File.Exists(strLogFile))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(strLogFile))
{
sw.WriteLine("Our application's log file.");
sw.WriteLine("Created "
+ DateTime.Now.ToString(strDateFormat));
sw.Close();
}
}

// This text is always added, making the file longer over time
// if it is not deleted or cleaned up.
using (StreamWriter sw = File.AppendText(strLogFile))
{
sw.WriteLine(DateTime.Now.ToString(strDateFormat) + ":");
sw.WriteLine("\t" + strToLog.Replace("\n", "\n\t"));
sw.Close();
}
}
}
catch (Exception e)
{
// probably b/c C:\temp\ doesn't exist or isn't accessible.
System.Diagnostics.Debugger.Break();

// insure that's the problem.
// In production, if you forget to remove this exception handler
// or to move log location to something valid on the server/box,
// it'll quietly fail.
}

}

Labels: , ,