在catch或c#中每个方法的内部调用日志方法的位置
本文关键字:方法 内部 日志 位置 调用 catch | 更新日期: 2023-09-27 18:04:07
实际上,我想以这样一种方式记录数据,它应该具有应用程序在c#中经历的方法,如果有错误,那么错误内容也应该被记录。问题是在哪里调用日志方法的catch内部或内部的每个方法?因为我有将近200个方法。
我写的代码是这样的:
public static bool Logging(System.Reflection.MethodBase methodInfo)
{
var fullMethodName = methodInfo.DeclaringType.FullName + "." + methodInfo.Name;
if (error_flag == false)
{
using (StreamWriter outputFile = new StreamWriter(path + @"'log.txt", true))
{
outputFile.WriteLine(fullMethodName + ": OK");
}
}
else
{
using (StreamWriter outputFile = new StreamWriter(path + @"'log.txt", true))
{
outputFile.WriteLine("'n'n --> Error in : " + fullMethodName);
}
}
return true;
}
//Logging Method 2
public static bool WriteErrorLog(Exception ErrorMessage)
{
using (StreamWriter outputFile = new StreamWriter(path + @"'log.txt", true))
{
outputFile.WriteLine("{0} Exception caught.", ErrorMessage);
}
return true;
}
,我必须从哪里调用这些方法??
我建议采用以下方法:
static void Main()
{
try
{
Log.Info("Start of process");
string input = StepOne();
StepTwo(input);
Log.Info("End of process");
}
catch(Exception e)
{
Log.Error(e);
}
}
public static string StepOne()
{
Log.Info("StepOne Completed");
return "Step One";
}
public static void StepTwo(string input)
{
Log.Info("StepTwo, input: " + input);
throw new ArgumentNullException("input");
}
- 使用现有的日志框架,例如Log4Net,而不是自己滚动。
- 在尽可能高的层添加一个try catch,让错误冒泡,直到你可以真正对它们做一些明智的事情。
- 为函数添加日志消息,这将是最有用的信息,例如你可以记录方法输入。 避免使用反射来获取方法名,你可能不需要记录单个方法名。无论如何,所有这些信息都会在堆栈跟踪中。