C# 网站中的日志记录错误

本文关键字:记录 错误 日志 网站 | 更新日期: 2023-09-27 17:56:07

我计划实现错误日志记录,编写类似以下内容的内容:

public static void WriteError(string errorMessage)
    {
        try
        {
            string path = "~/Error/" + DateTime.Today.ToString("dd-mm-yy") + ".txt";
            if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
            }
            using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                w.WriteLine("'r'nLog Entry : ");
                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
                              ". Error Message:" + errorMessage;
                w.WriteLine(err);
                w.WriteLine("__________________________");
                w.Flush();
                w.Close();
            }
        }
        catch (Exception ex)
        {
            WriteError(ex.Message);
        }
    }

我的问题是:由于它是一个网站,我将同时拥有多个用户。在这种情况下,如果多个用户同时遇到异常并尝试写入同一个文件,它会再次给我一个异常,对吗?在这种情况下,如何为并发用户正确实现错误日志记录?还是会起作用?

提前谢谢。

C# 网站中的日志记录错误

我建议您使用已建立的日志记录框架,例如NLog或log4net。我过去在许多项目中使用过log4net,它可以完美地处理这种情况。

编辑:

作为进一步的评论,除了处理来自多个线程的日志消息外,log4net 还允许您管理日志文件的增长大小,并通过 RollingFileAppender 提供内置的滚动日志机制。

除了使用 NLog 或其他日志库之外,锁定这种情况的方式是使用互斥锁。我建议mutex,而不是lock(),因为可以捕获所有可能引发错误的池/线程。

在 MSDN 上,有关于mutex和示例的详细信息:

http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx

一个简单的例子

public static void WriteError(string errorMessage)
{
    var mut = new Mutex(true, "LogMutexName");
    try
    {   
        // Wait until it is safe to enter.
        mut.WaitOne();
        // here you open write close your file
    }
    finally
    {
        // Release the Mutex.
        mut.ReleaseMutex();
    }   
}