Peekay
Peekay

Reputation: 451

Exception Logging Using StackTrace

I wanted to log the Exception details Filename , FileLineNo, Method Name (where the exception occured) This is working using the StackTrace class But some times i am getting the File Line No and Method Name as null How shall i track Exception Details all the time when an Exception occur

here is my code

Public Shared Sub LogException(ByVal ex As Exception)

Dim trace As Diagnostics.StackTrace = New Diagnostics.StackTrace(ex, True)
LogInfo(String.Format("Error Message :{0}  => Error In :{1}  => Line Number :{2} => Error Method:{3}",
                              ex.Message, trace.GetFrame(0).GetFileName(),
                              trace.GetFrame(0).GetFileLineNumber(),
                              trace.GetFrame(0).GetMethod().Name))
End Sub

Upvotes: 0

Views: 2746

Answers (3)

StingyJack
StingyJack

Reputation: 19469

So, the answer to probably all of your questions at once is: "The caught exception will have all of the details it can possibly have."

Your public shared sub LogException is getting an Exception object that is already going to have most of that information. So, you can just do...

LogInfo(ex.ToString())

...and get as much detail as possible.

There are going to be cases where you may not have file name or line numbers, and in some cases the LogInfo statement you have will throw an exception itself. This explains how to reliably get these details, though it comes with potential security risks.

I have found that the type of exception and the stack trace information contained in Exception.ToString() is usually enough to pinpoint the actual errors. When it isn't, its usually a problem with the structure of the code.

Upvotes: 4

lc.
lc.

Reputation: 116478

1) You can get the stack trace from inside the Exception object using Exception.StackTrace. You don't need to create a new one.

2) If the exception was thrown from somewhere you do not have debugging info (for example inside the framework), you may simply not have a line number or source filename to get.

Upvotes: 1

John Saunders
John Saunders

Reputation: 161773

The exception already contains the full stack trace. You don't need to create a new one.

Upvotes: 2

Related Questions