Write to a log file in ASP.NET

2019-02-06 23:58发布

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?

3条回答
来,给爷笑一个
2楼-- · 2019-02-07 00:34

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
    }
}
查看更多
不美不萌又怎样
3楼-- · 2019-02-07 00:36

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.

查看更多
叼着烟拽天下
4楼-- · 2019-02-07 00:51

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.

查看更多
登录 后发表回答