Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter out non-user code methods from StackTrace

Tags:

c#

.net

asp.net

I am trying to implement somewhat more sophisticated error handling. To achieve my goal, I need to filter out non-user code methods (frames) from curent StackTrace.

In ASP.NET typical StackTrace as you can probably guess the are many methods that are quite irrelevant for debugging purposes as they are outside of the user code. Visual studio gives you option to filter out this non-user code (frames) so I am guessing its possible. However after about 30 minutes of exploring methods and properties of StackFrames (and methods, modules, assemblies, ... ) I couldnt find any that could be used to identify "system" frames.

I have ended up with manual specification of which modules I want to log (module is part of assembly, in my case 1:1).

Is there any better way to do this? Simply include everything outside core ASP.NET.

like image 472
NeverStopLearning Avatar asked Nov 19 '12 10:11

NeverStopLearning


1 Answers

StackFrame class has the GetMethod() member function, from retrieved MethodBase object.

If all you need is a naive filter you may do one of these:

  • Strip out every method in a class which starts with "System." or "Microsoft." (because all .NET libraries are placed there).
  • Find the assembly where a method is (see forward) then check for AssemblyCompanyAttribute and filter assemblies made by "Microsoft Corporation"). This is better than previous method because sometimes I saw libraries which put their own types inside System namespace.

If you need something more you can get the module (MethodBase.Module) where that method is defined. Now you have two options:

  • If all your assemblies are signed you can show only methods with that public key token (get the assembly where the module is defined with Module.Assembly property, build an AssemblyName object with Assembly.FullName then check the public key for AssemblyName.KeyPair property, it must match your public key token (simply compare with GetExecutingAssembly()).
  • If not all your assemblies are signed you can do the same operation but filtering out all the assemblies that matches the public key token of system assemblies (this may be the simplest case and it'll include 3rd part libraries too).

Please note that not all system assemblies have the same public key token (even within the same Framework version) so you must collect and check a list of keys (just browse c:\windows\assembly to read them). A good approach could be to check for public key and then apply a second filter using AssemblyCompanyAttribute.

like image 89
Adriano Repetti Avatar answered Sep 25 '22 08:09

Adriano Repetti