How to format Exception's stack trace in C#?

早过忘川 提交于 2019-12-05 18:51:51

问题


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.

How can I do that?


回答1:


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

What you can do is this:

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.


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);



回答2:


Check out the System.Diagnostics.StackFrame class and the GetFileName method. You can write a method that will get the stack trace and the names of the source files that you can call in your exception handler.



来源:https://stackoverflow.com/questions/2372186/how-to-format-exceptions-stack-trace-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!