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

查看:235
本文介绍了如何格式化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);



它给你的堆栈跟踪对象,为您提供所需的所有信息。在我的情况下,它是如何避免不必处理局部异常文本,但我想像你可以使用你的需求相同的方法。

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参数的构造。我在这里看到这样的构造:堆栈跟踪(例外五,布尔fNeedFileInfo),我找不到有问题的实际代码,但现在我猜你需要真正传递给这样的说法。我猜实验是这里的关键

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天全站免登陆