如何将异常记录到文件

本文关键字:文件 记录 异常 | 更新日期: 2023-09-27 18:33:12

我一直在尝试将异常记录到文件中。我可以得到异常及其所有细节,当我逐步完成课程时,StreamWriter logWriter似乎没有做我认为它会做的事情。

 public static void Write(Exception exception)
{
    string logfile = String.Empty;
    try
    {
        logfile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ErrorLog"]).ToString();
        StreamWriter logWriter;
        if (File.Exists(logfile))
        {
            logWriter = File.AppendText(logfile);
        }
        else
        {
            logWriter = File.CreateText(logfile);
            logWriter.WriteLine("=>" + DateTime.Now + " " + " An Error occurred: " + exception.StackTrace +
                                " Message: " + exception.Message + "'n'n");
            logWriter.Close();
            throw exception;
        }
    }
    catch (Exception e)
    {
        throw;
    }
}

我认为 logWriter 会将异常详细信息写入 File.AppendText(日志文件) but it doesn't and just jumps straight out the if statement. All the details of the exception are in the else statement, I have tried to put this in the if' 条件,但抛出异常!

如何将异常写入文件。我从CodeProject那里得到了代码。除了将异常写入文件外,一切正常。

如何将异常记录到文件

正确尝试并将异常抛出方法之外:

public static void Write(Exception exception)
{
    string logfile = String.Empty;
        try
    {
        logfile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ErrorLog"]).ToString();
        if(File.Exists(logfile))
        {
            using(var writer = new StreamWriter(logfile, true))
            {
                writer.WriteLine(
                    "=>{0} An Error occurred: {1}  Message: {2}{3}", 
                    DateTime.Now, 
                    exception.StackTrace, 
                    exception.Message, 
                    Environment.NewLine
                    );
            }
        }
    }
    catch(Exception e)
    {
        throw;
    }
}

把它扔到外面:

catch(Exception e)
{
    Write(e);
    throw;
}

此代码段用于写入文件

public static bool WriteResult(string result)
        {
            using (StreamWriter sr = File.AppendText("result.txt"))
            {
                sr.WriteLine(result);
                sr.Flush();
                return true;
            }
            return false;
        }

对于您来说,您必须对其进行一些调整以满足您的要求:

public static void Write(Exception exception) {
    try {
        using(StreamWriter sr = File.AppendText("result.txt")) //new StreamWriter("result.txt", Encoding. ))
        {
            sr.WriteLine("=>" + DateTime.Now + " " + " An Error occurred: " + exception.StackTrace +
                " Message: " + exception.Message + "'n'n");
            sr.Flush();
        }
        catch (Exception e) {
            throw;
        }
    }

我写的一个很好的模板方法适用于每个项目。

  private static void AddLog(string strMsg)
    {
        #region logfolder creation
        if (!System.IO.Directory.Exists("C:''appname"))
        {
            System.IO.Directory.CreateDirectory("C:''appname");
            if (!System.IO.Directory.Exists("C:''appname''Logs"))
            {
                System.IO.Directory.CreateDirectory("C:''appname''Logs");
            }
        }
        #endregion
        #region logfile creation
        FileStream fsc;
        logFileName = "C:''appname''Logs''appnameLog_" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + ".txt";
        if (!System.IO.File.Exists(logFileName))
        {
            fsc = new FileStream(logFileName, FileMode.Create, FileAccess.Write);
            fsc.Close();
        }
        #endregion
        #region logging
        using (FileStream fs = new FileStream(logFileName, FileMode.Append, FileAccess.Write))
        {
            using (StreamWriter sr = new StreamWriter(fs))
            {
                try
                {
                    sr.WriteLine(strMsg);
                }
                catch (Exception exc)
                {
                    EventLogEntry(exc.ToString().Trim(), EventLogEntryType.Error, 7700);
                }
            }
        }
        #endregion
    }