Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format Exception's stack trace in 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.

How can I do that?

like image 891
Dawid Ohia Avatar asked Mar 03 '10 14:03

Dawid Ohia


People also ask

How do I get full stack trace?

We can obtain a stack trace from a thread by calling the getStackTrace() method on the Thread instance. It returns an array of StackTraceElement, from which details about stack frames of the thread can be found.

How do I save a stack trace?

If you want to save a stack trace for later use or create a link to it, click the Share button store the stack trace.

How do I get StackTrace from exception?

getStackTrace(); String exception = ""; for (StackTraceElement s : stack) { exception = exception + s. toString() + "\n\t\t"; } System. out. println(exception); // then you can send the exception string to a external file. }


1 Answers

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);
like image 143
Lasse V. Karlsen Avatar answered Oct 19 '22 22:10

Lasse V. Karlsen