在C#中记录异常 [英] logging exception in c#

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

问题描述

日志例外
,这是低于它用于在文本文件中记录异常的代码。
在这里,我只得到错误的能解密。



但它没有告诉我哪里有异常出现在哪一行。
将任何ONR告诉我howi可以achive这让我得到即使在出现异常的行号。

 
{

}
赶上(异常前)
{
Console.WriteLine(ex.Message);
}

#地区WriteLogError
///<总结>
///写文件
错误日志///< /总结>
///< PARAM NAME =的errorMessage>< /参数>
公共无效WriteLogError(字符串的errorMessage)
{

{
路径字符串=〜/错误/+ DateTime.Today.ToString(DD-MM -YY)+.TXT;
如果(!File.Exists(System.Web.HttpContext.Current.Server.MapPath(路径)))
{
File.Create(System.Web.HttpContext.Current.Server。 。的MapPath(路径))关闭();
}
使用(StreamWriter的W = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(路径)))
{
w.WriteLine(\ r\\\
Log输入:);
w.WriteLine({0},DateTime.Now.ToString(CultureInfo.InvariantCulture));
字符串ERR =错误:+ System.Web.HttpContext.Current.Request.Url.ToString()+
。错误消息:+的errorMessage;
w.WriteLine(ERR);
w.WriteLine(__________________________);
w.Flush();
w.Close();
}
}
赶上(异常前)
{
WriteLogError(ex.Message);
}

}

#endregion


解决方案

我发现,在C#中记录异常的最简单方法是调用的ToString()方法:

 
{

}
赶上(异常前)
{
Console.WriteLine(ex.ToString());
}

这通常给给你你需要的所有信息,如错误消息,堆栈跟踪,以及任何额外的异常特定上下文信息。 (但是请注意,堆栈跟踪将只显示您的源文件和行号,如果你有你的应用程序的调试信息编译)



值得注意的是,然而,看到一个完整的。堆栈跟踪可以为用户相当offputting所以只要有可能,你应该尽量处理异常并打印出一个更友好的错误消息。



另外要注意的 - 你应该有一个全功能的日志框架取代你的方法 WriteLogError (如 log4net的,而不是试图编写自己的。



您测井方法不是线程安全的(日志文件可能会与日志结束被混合的信息与对方),并如果赶上一个例外绝对不应该称自己 - 这将意味着发生的同时记录错误任何异常可能会导致难以诊断的StackOverflow例外



我可以建议如何解决这些事情,但你会好得多服只使用一个合适的日志框架。


logging exception this is below code which is used for logging exception in a text file. here i am getting only the decription of the error.

but it is not telling me where the exception occured at which line. would any onr tell me howi can achive that so that i get even the line number where the exception occured.

    try
     {

     }
   catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
      }

    #region WriteLogError
        /// <summary>
        /// Write an error Log in File
        /// </summary>
        /// <param name="errorMessage"></param>
        public void WriteLogError(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)
            {
                WriteLogError(ex.Message);
            }

        }

        #endregion

解决方案

I find that the easiest way to log exceptions in C# is to call the ToString() method:

try
{

}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}

This gives usually gives you all the information you need such as the error message and the stack trace, plus any extra exception specific context information. (however note that the stack trace will only show you source files and line numbers if you have your application compiled with debug information)

It is worth noting however that seeing a full stack trace can be fairly offputting for the user and so wherever possible you should try to handle exceptions and print out a more friendly error message.

On another note - you should replace your method WriteLogError with a fully featured logging framework (such as Log4Net) instead of trying to write your own.

Your logging method is not thread safe (your log file will probably end up with log messages being intermingled with each other) and also should definitely not call itself if you catch an exception - this will mean that any exceptions that occur whilst logging errors will probably cause a difficult to diagnose StackOverflow exception.

I could suggest how to fix those things, however you would be much better served just using a proper logging framework.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆