我在C#WinForms项目中设置了一个日志记录系统,该系统写入日志txt文件。典型的错误消息如下所示:
Error :
8:34:48 AM Tuesday, April 21, 2020
:
:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.Collections.ArrayList.get_Item(Int32 index)
at System.Windows.Forms.DataGridViewColumnCollection.get_Item(Int32 index)
at CrossReferenceTool.frmXRefTool.DefineControlsLayout() in <PathToSourceCsFile>:line 306
有没有办法捕获该错误消息的一部分?具体来说,我想提取有问题的方法(在这种情况下为
DefineControlsLayout()
)和行号。
最佳答案
实例化一个新的StackTrace并在发生任何异常后从中记录详细信息。
我使用的原始链接:https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.stacktrace.getframe?view=netframework-4.8
范例程式码using System.Diagnostics;
try
{
throw new Exception("Fail");
}
catch (Exception e)
{
StackTrace st = new StackTrace(e);
// Display the most recent function call.
StackFrame sf = st.GetFrame(0);
Console.WriteLine();
Console.WriteLine(" Exception in method: ");
Console.WriteLine(" {0}", sf.GetMethod());
if (st.FrameCount > 1)
{
// Display the highest-level function call
// in the trace.
sf = st.GetFrame(st.FrameCount - 1);
Console.WriteLine(" Original function call at top of call stack):");
Console.WriteLine(" {0}", sf.GetMethod());
// will only work if .pdb is included
var lineNumber = sf.GetFileLineNumber();
var fileName = sf.GetFileName();
}
}
关于c# - 从C#WinForms错误消息中提取特定信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61345101/