Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将每个错误附加到文本文件_C#_Asp.net_Logging - Fatal编程技术网

C# 将每个错误附加到文本文件

C# 将每个错误附加到文本文件,c#,asp.net,logging,C#,Asp.net,Logging,我使用此语法将错误写入文本文件,以便登录我的Global.axax——它每次都会覆盖,只记录最近的错误。虽然这是有帮助的,但它并不像我需要的那样有帮助。如何记录引发的每个错误 这是我当前的代码,只记录最近的: void Application_Error(object sender, EventArgs e) { Exception CurrentException = Server.GetLastError(); Server.ClearError(); if (Cu

我使用此语法将错误写入文本文件,以便登录我的
Global.axax
——它每次都会覆盖,只记录最近的错误。虽然这是有帮助的,但它并不像我需要的那样有帮助。如何记录引发的每个错误

这是我当前的代码,只记录最近的:

void Application_Error(object sender, EventArgs e)
{ 
    Exception CurrentException = Server.GetLastError();
    Server.ClearError();
    if (CurrentException != null)
    {
        try
        {
            using (StreamWriter sw = new StreamWriter(Server.MapPath("HereAreErrors.txt")))
            {
            sw.WriteLine(CurrentException.ToString());
            sw.Close();
            }
        }
        catch (Exception ex) { }
    }
}

正如其他人所说,最好使用现有的日志工具来处理日志记录。它们有无数的特性,最重要的是,它们是由其他人维护的

话虽如此,为了回答所问的问题,以下是如何解决您的问题。如果文件不存在,它还可以创建该文件

void Application_Error(object sender, EventArgs e)
{ 
  Exception CurrentException = Server.GetLastError();
  Server.ClearError();
  if (CurrentException != null)
  {
    try
    {
        File.AppendAllText(Server.MapPath("HereAreErrors.txt"), CurrentException.ToString());
    }
    catch (Exception ex) { }
  }
}

日志记录考虑使用类库,否则您可以使用,如果您想“追加到文本文件”,然后有一个方便的类和方法。此外,无需使用日志框架手动重新发明轮子。做一些研究,找到一个很好的现有产品,比如Elmah。我正在使用IIS——这个Apache产品也可以吗?是一个软件基础。他们的“HTTP服务器”产品通常称为Apache,但不是他们唯一的产品。他们也为其他框架创建工具。其中log4net就是其中之一。log4net与IIS配合使用非常好。对于寻找答案的人来说,这个语法为我指明了正确的方向,因为File.AppendAllText包含两个参数。但我必须将变量CurrentException从Exception转换为string,然后才能将其作为File.AppendAllText.Good catch的第二个参数传入。我修复了使用字符串处理的方法调用。