将异常写入日志文件。

编程入门 行业动态 更新时间:2024-10-07 11:23:40
本文介绍了将异常写入日志文件。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个接受一般异常作为参数的方法。 每当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。

更多推荐

将异常写入日志文件。

本文发布于:2023-11-23 21:45:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622938.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   文件   日志

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!