Custom Text File Publisher for Exception Management Application Block

I needed to create a publisher for exceptions to a text file (XML would be better but the requirement was for text…). I based my publisher on this article I found on C# Corner. But it has one problem associated with using files, that unfortunately loomed large. Concurrency. To a certain extent the code handled the problem by tossing the error into the Event Log if the provider threw an error, but this was not acceptable for my requriement. So I needed to modify the code to handle the issue. Essentially, I modified the overriden Publish procedure to trap the error related to the StreamWriter and then sleep for a set amount of time and try again. After too many failures at writing to the file the error eventually gets written to the event log (so it is not lost).

privateconst int WriteAttempts = 5;
private const int SleepTime = 500;

void IExceptionPublisher.Publish(Exception exception, NameValueCollection additionalInfo, NameValueCollection configSettings)
{

    // Read and set up configuration
    SetConfig(configSettings);

    // Create fileName
    string logFilePath = CreateLogFilePath();

    // Create Message
    string logMessage = CreateLogMessage(exception, additionalInfo);

    int attempts = 0;
    bool written = false;

    // Write the entry to the log file.
    while(!written && attempts <= WriteAttempts)
    {
       
try
       
{
            // Append to file if exists or create new file
           
using ( FileStream fs = File.Open(logFilePath, FileMode.Append,FileAccess.Write))
            {
               
using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write(logMessage);
                    written =
true;
                }
            }
        }
       
catch
       
{
            attempts++;
            Thread.Sleep(SleepTime);
         }
    }
    if(attempts > WriteAttempts)
    {
       
throw(exception);
    }

}

Posted on:

Comments are closed.