Write to a log file in ASP.NET

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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

Method 3

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x