user1670407
user1670407

Reputation:

C# File Open frequently, already open exception

Hey so I have a logger class that is called frequently, sometimes when its called fast repeatedly it will throw an exception that the file is already open being used by another application. The only way we found a way around this was to catch the exception then try to open it again... I'm not sure how to handle this properly.

    /// <summary>
    /// Open a log file based on a date
    /// </summary>
    /// <param name="date"> Date of the file to open </param>
    public static void OpenLogFile(DateTime date)
    {
        while (true)
        {
            try
            {
                logStream = File.Open("Logs/ems." + date.ToString("yyyy-MM-dd") + ".log", FileMode.Append);
                break;
            }
            catch
            {
                continue;
            }
        }
    }




    /// <summary>
    /// Writes to a log file the specified input
    /// </summary>
    /// <param name="input"> Content to write to the log file </param>
    public static void Log(string className, string methodName, string input)
    {
            OpenLogFile(DateTime.Now);

            using (StreamWriter s = new StreamWriter(logStream))
            {
                s.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + '[' + className + '.' + methodName + "] " + input);
            }

            CloseLogFile(); 
    }




    /// <summary>
    /// Closes the current log file
    /// </summary>
    public static void CloseLogFile()
    {
        if (logStream != null)
        {
            logStream.Close();
            logStream = null;
        }
    }

Upvotes: 0

Views: 830

Answers (2)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137408

Since this is a log file, I think the obvious (and correct) solution, is to leave the file open for the duration of your program's execution.

If you don't want to use an already-implemented 3rd party logger, like Apache's log4net, you could write your own little logger class that uses thread-safe mechanisms for writing lines to the file.

It would probably be a static class, or singleton. Generally, execution at the beginning and end of your program is quite predictable, so it should be clear where to initialize, and close out the object/class.

Upvotes: 5

spender
spender

Reputation: 120450

A bit of order is required, not a disk free-for-all. Store log messages in a queue and have a single thread dequeue and write items.

Upvotes: 1

Related Questions