将异常写入日志文件。 [英] Writing Exception to a log file.

查看:74
本文介绍了将异常写入日志文件。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受一般异常作为参数的方法。

每当try catch抛出异常(指定异常类型)时我想将它传递给我的方法。



最终会写一个日志文件。



任何人都可以帮忙。

I have a method which accepts a general exception as parameter.
Whenever a try catch throws exception (with exception type specified) i wants to pass it to my method.

Which will ultimately write a log file.

can anyone help.

推荐答案

在web.config中添加一个LogFilePath条目

Add A LogFilePath entry in web.config
<appSettings>
   <add key="LogFilePath" value="C:\\LogFile.txt"/>
 </appSettings>



使用静态方法WriteLog()创建一个Looger类;


Create A Looger Class With static method WriteLog() ;

public class Logger
{

    public static string LogFile { get { return ConfigurationManager.AppSettings[&quot;LogFilePath&quot;]; } }

    public static void WriteLog(Exception ex)
    {
        using (FileStream fs = new FileStream(LogFile, FileMode.Append, FileAccess.Write))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.WriteLine(ex.Message+&quot;||&quot;+ex.StackTrace);
            }
        }
    }
}



现在您可以在应用程序中调用WriteLog方法


Now You can call your WriteLog mthod in your Application as

try
      {
          throw new Exception("new exception got");
      }
      catch (Exception ex)
      {
          Logger.WriteLog(ex);
      }



注意:请完全访问要写入日志文件的文件夹。在这种情况下,它是C Drive。


这篇关于将异常写入日志文件。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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