RobLog

Summary


This is a logging function that I use to rapidly troubleshoot issues when I don't have the ability to use some form a of a debugger. It writes to a log file at c:\temp\roblog.txt. It uses a mutex so errors aren't thrown in the event that multiple processes are running and writing to roblog.txt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public void RobLog(string message)
{
    try
    {
        using (var mutex = new Mutex(false, "RobLogLock"))
        {
            var mutexAcquired = false;
            try
            {
                // acquire the mutex (or timeout after 60 seconds) will return false if it timed out
                mutexAcquired = mutex.WaitOne(60000);
            }
            catch (AbandonedMutexException)
            {
                // abandoned mutexes are still acquired, we just need to handle the exception and treat it as acquisition
                mutexAcquired = true;
            }

            // if it wasn't acquired, it timed out, so can handle that how ever we want
            if (!mutexAcquired)
            {
                throw new Exception("Unable to obtain a lock on the process to write to the roblog file");
            }

            // otherwise, we've acquired the mutex and should do what we need to do,
            // then ensure that we always release the mutex
            try
            {                       
                using (TextWriter tw = new StreamWriter(@"C:\temp\roblog.txt", true))
                {
                    // write a line of text to the file
                    tw.WriteLine(message);
                }
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }
    }
    catch { }
}

No comments:

Post a Comment

} else { }