Stack Trace for logging in .NET

荒凉一梦 提交于 2019-12-07 07:37:00

问题


I've written a logger/exceptionfactory module, which uses System.Diagnostics.StackTrace, to get attributes from calling methods and their declaring types. However I noticed, that if I run the code outside of Visual Studio in Release mode, some of my shorter methods get inlined and missing from the stack trace. Now I have no way to test whether a method will get inlined in runtime, but I do not want to [MethodImpl(MethodImplOptions.NoInlining)] every important method. But if a method from my base classes will be missing because of it, I can misread the layer and operation information and that could lead to false log or misparameterized exceptions.

Is there a rule of thumb what gets inlined where and when? Are virtual methods, static methods, base class methods treated any differently? Do I only have to worry about inlining inside assembly? Inside namespace?


回答1:


Yes, there are some rules but they are heuristics used by the JIT compiler and these heuristics can change at a moment's notice.

  1. Virtual methods cannot be inlined.
  2. Interface methods, on the other hand, may be inlined although I am not 100% sure whether or not this would collapse the stack trace.
  3. Static methods and non-virtual instance methods can certainly be inlined.
  4. Inlining may cross namespaces (of course) and assemblies (not so obvious) because it happens at run-time, when the JIT compiles the method call.
  5. "Heavy" methods will not be inlined. This depends on the definition of "heavy", and is part of the heuristics the JIT applies.

Some of the heuristics for "heavy" that I'm aware of:

  • Methods which use exception handling (i.e. try-catch or try-finally blocks) are not inlined.
  • Methods with large code (~32 IL bytes but I may be remembering this wrong) are not inlined.
  • Methods with loops are not inlined (unless the loop can be completely unrolled or eliminated).



回答2:


The heuristics are all implementation details of the jitter, meaning that they aren't officially documented and are presumably subject to change at any time.

Having said that, here are some articles that you might find interesting (although some of them are a bit long-in-the-tooth now):

  • Some Thoughts About Inlining
  • More on inlining...
  • Jit Optimizations: Inlining (I)
  • Jit Optimizations: Inlining (II)
  • To Inline or not to Inline: That is the question


来源:https://stackoverflow.com/questions/4849709/stack-trace-for-logging-in-net

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