如何在C#中格式化异常的堆栈跟踪? [英] How to format Exception's stack trace in C#?

查看:167
本文介绍了如何在C#中格式化异常的堆栈跟踪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当显示异常时(或更通用的 - 当转换为字符串时)显示堆栈跟踪。我想做的是更改源代码的文件路径的格式。

When Exception is displayed (or more general - when it is converted to String) stack trace is shown. What I want to do is to change the format of source code's file paths shown in such trace.

具体来说,我想离开文件名(没有完整路径)或显示只有从项目的基本目录开始的那部分路径。完整的路径通常是不必要的,并且会使整个消息混乱。

Specifically I would like to leave filenames only (without full path) or show only that part of path which starts with project's base directory. Full paths are usually unnecessary and clutter the whole message.

我该怎么做?

推荐答案

我问了一个类似的问题,虽然不完全相同,但这里:在C#中打印堆栈跟踪信息

I asked a similar question, although not entirely the same, here: Print stack trace information in C#.

你可以做的是这样的:

var trace = new System.Diagnostics.StackTrace(exception);

这给你一个 StackTrace 对象,为您提供所需的所有信息。在我的情况下,这是关于避免不必处理本地化的异常文本,但我想象你可以使用相同的方法来满足您的需要。

which gives you a StackTrace object that gives you all the information you need. In my case it was about avoiding having to deal with localized exception text, but I'd imagine you can use the same approach for your needs.

修改:我注意到我已经添加了一个注释到接受答案我的问题与构造函数的needFileInfo参数相关。我在这里看到这个构造函数: StackTrace(Exception e,bool fNeedFileInfo) ,我现在找不到相关的实际代码,但我猜想你需要将 true 传递给该参数。我猜测实验是这里的关键。

Edit: I note that I have added a comment to the accepted answer to my question related to a "needFileInfo" parameter to the constructor. I see this constructor here: StackTrace(Exception e, bool fNeedFileInfo), I can't find the actual code in question right now but I would guess you need to pass true to that argument. I guess experimentation is the key here.

换句话说,我猜代码应该是这样的:

In other words, I guess the code should be this:

var trace = new System.Diagnostics.StackTrace(exception, true);

这篇关于如何在C#中格式化异常的堆栈跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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