本文介绍了将异常写入日志文件。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个接受一般异常作为参数的方法。 每当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["LogFilePath"]; } } 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+"||"+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。
更多推荐
将异常写入日志文件。
发布评论