0

I want to log the current location of code in a logger with the same details that exceptions have, e.g.:

   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()

What methods are available for this, or is it best to rather throw an exception and then handle it with try catch?

Corne Beukes
  • 1,759
  • 4
  • 14
  • 18

1 Answers1

0

Take a look at System.Diagnostics.StackTrace

From a logging method, you can also do this to find the name of the method that called your logging function:

(new StackFrame(1)).GetMethod().Name

The "1" in that code means the prior stack frame: the method that called this function. "0" would be the current entry. Also be careful of inlining.

Finally, since this is tagged for asp.net, I need to talk about async. The async coding style featured in modern ASP.Net Core can play all kinds of havoc with your stack traces. Be aware things may not be as you expect when you look at these.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794