如何将异常记录到文件中

时间:2014-12-05 13:07:02

标签: c#

我一直在尝试将异常记录到文件中。我可以通过它的所有细节获得异常,当我逐步完成课程时,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(logfile)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获得了代码。除了将异常写入文件外,一切正常。

3 个答案:

答案 0 :(得分:0)

此代码段可写入文件

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

    }

答案 1 :(得分:0)

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

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

答案 2 :(得分:-1)

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

  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
    }