在C#网站错误记录

在C#网站错误记录

本文介绍了在C#网站错误记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我计划实施的错误日志写类似的东西来:

I am planning to implement error logging writing something similar to this:

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

    }

我的问题是这样的:因为它是一个网站,我将同时有多个用户。在这种情况下,如果多个用户遇到在同一时间异常和尝试写入同一个文件,它会再次给我权的例外?在这种情况下,我该如何正确地执行错误日志记录用户同时使用?或将这项工作?

My question is this: Since it is a website, I will have multiple users simultaneously. In that case, if multiple users encounter exceptions at the same time and try to write to the same file, it will again give me an exception right? In that case, how do I implement error logging correctly for simultaneous users? Or will this work?

先谢谢了。

推荐答案

除了使用NLOG或其他日志库,锁定该案件的方式是互斥。我建议互斥,而不是锁(),因为可以捕捉所有池/线程可能会引发错误。

Beside using NLog or other log library, the way you lock this cases is with mutex. I suggest mutex, and not lock() because can catch all pools/threads that may throw an error.

在MSDN有关于互斥和示例的详细信息:

On MSDN there are the details about mutex and examples:

一个简单的例子

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();
    }
}

这篇关于在C#网站错误记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 05:40