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;
}
}