日志写入文本文件是否会影响网站的性能?

时间:2013-08-20 11:49:54

标签: c# asp.net

我有一个ASP.NET网站。我正在编写日志文件以获取页面的总时间跨度。写入txt文件的日志会影响我的程序的性能吗?我正在OnUnload等事件中记录此事。

string logString = string.Format("The total time span for the '{0}' is {1}ms",
                                 _page, 
                                 span.TotalMilliseconds);
WriteLog(logString);

日志摘录:

8/6/2013 05:38:27]:The total time span for the 'Assign' is 3121.1785ms
[8/6/2013 05:38:27]:The total time span for the 'Assign' is 5.0002ms
[8/6/2013 05:38:27]:The total time span for the 'Assign' is 5.0003ms
[8/6/2013 05:38:27]:The total time span for the 'Assign' is 4.0002ms
[8/6/2013 05:38:27]:The total time span for the 'Assign' is 5.0003ms
[8/6/2013 05:38:27]:The total time span for the 'Assign' is 6.0004ms

4 个答案:

答案 0 :(得分:1)

嗯,影响很可能不会受到影响。至少不会引人注意,只要你没有记录太多。您应该查看log4net之类的日志框架。它会为你做很多事情,就像在给定数量的日志之后写入txt文件一样。这将减少写入文件的数量。

如果您想自己动手,我建议您在另一个线程上执行日志,如下所示:

var thread = new Thread(message =>
    {
        // write message to txt file.
    });

thread.Start("This is a log statement");

这样它就不会占用你的主线程。但是,使用多个线程写入文件非常危险。你需要一些锁定:

private static readonly object _writeLock = new object();

var thread = new Thread(message =>
    {
        lock (_writeLock)
        {
            // write message to txt file.
        }
    });

thread.Start("This is a log statement");

现在您确定只有一个线程写入该文件。我仍然建议使用log4net或任何其他为你完成这项工作的框架。

答案 1 :(得分:1)

你正在做某事任何事情会影响你的表现。写入文件相对较慢,所以是的,它会为您的表现做某些。多少取决于您的硬件配置,坦率地说,取决于您未显示的WriteLog()方法。

除此之外,只要一个进程尝试向日志写入内容而另一个进程执行相同操作,您就会遇到问题。

如果要最小化性能影响,请尝试尽快卸载日志记录,最好是另一个线程。

答案 2 :(得分:0)

是的,它会影响应用程序的性能,效果与用户数量成正比

答案 3 :(得分:0)

如果您只需要时间,IIS日志默认具有该功能。

Default IIS log format(说IIS6和win server 2003,但这也是新版本的默认设置。

time-taken: The length of time that the action took, in milliseconds.
相关问题