Reputation: 45
The error occurs randomly, my guess is when there is heavy traffic, but i'm having a hard time replicating it. This functionality runs everytime a business transaction is initiated.
Error: System.IO.IOException: The process cannot access the file '' because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
private void writeToTrafficLogFile(string data, string filePath)
{
try
{
StreamWriter logWriter;
if (!File.Exists(filePath))
{
logWriter = new StreamWriter(filePath);
}
else
{
logWriter = File.AppendText(filePath);
}
logWriter.WriteLine(DateTime.Now);
logWriter.WriteLine(data);
logWriter.WriteLine();
logWriter.Close();
}
catch (Exception error) {
sendLoggingErrorEmail(error, "Error Writing writeToTrafficLogFile", "Error Writing writeToTrafficLogFile.\r\n");
}
}
#endregion
}
Upvotes: 0
Views: 2162
Reputation: 1377
You're probably calling that from multiple threads at the same time...
There are two possible solutions:
A: Create a single thread that writes to the log file from a string that other threads can write to. -- Clarification edit: Have a class with code like
public static List<string> logme = new List<string>();
// Launch LogLoop as a thread!
public static void logloop()
{
while (true)
{
while (logme.Count > 0)
{
File.AppendAllText("log.txt", logme[0] + "\r\n");
logme.RemoveAt(0);
}
Thread.Sleep(500);
}
}
// Oh, and whenever you want to log something, just do:
logme.add("Log this text!");
B: Use a Lock on the log writer.
Upvotes: 0
Reputation: 32953
It might be easier and more bulletproof to switch to an existing, well tested logging solution. Several exist, have a look at dotnetlogging.com where dozens are listed. I can't recommend any, right now I am stuck with log4net but I can't recommend it.
Upvotes: 3