I am writing event data to a log file in an asp.net httphandler by using the File.AppendAllText method. I am concerned with what will happen when multiple requests are received simultaneously. Does AppendAllText lock the file it's writing to?
+1
A:
You can use My.Log to write to log files.
Edit: If you use the FileLogTraceListener, that listener is thread-safe.
Doing this also allows you to control and configure the logging through the web.config file.
NYSystemsAnalyst
2008-11-12 18:38:38
+4
A:
no, you should have a static lock object guarding the log-file write, e.g.
public static object LockingTarget = new object();
public void LogToFile(string msg)
{
lock(LockingTarget)
{
//append to file here as fast as possible
}
}
Steven A. Lowe
2008-11-12 18:39:16
Pay attention to IIS WebGarden. AFAIK you have different process --> different static object. So yon could get a concurrency conflict.
Fabrizio
2010-02-09 10:01:57
Fabrizio is right, all bets are off if you're using a web farm; i suggest logging to the database instead in that case. You probably don't want 50 servers trying to write to the same text file anyway!
Steven A. Lowe
2010-02-09 15:06:52
+4
A:
I recommend using the TextWriterTraceListener
instead of trying to manage this your self.
It is very simple to setup and use:
TextWriterTraceListener logListener = new TextWriterTraceListener("C:\log.txt", "My Log Name");
Trace.Listeners.Add(logListener);
And then to log something:
Trace.WriteLine("Log this text");
It is very simple to use and also there are many different types of listeners for SQL, Event Log, text file, etc. So you won't have to adjust your code if you want to change out the listener.
Nick Berardi
2009-07-08 12:12:22