Using the StackTrace Class in a Production Environment to Get Call Method Information

We have a "log" class that uses Relection.MethodBase to send current class information to the log.

The reflection.MethodBase property occurs in the class itself.

Nevertheless, I would like to transfer this material to one external class of type "log" singleton type.

In this scenario, the outer log class should receive CALLING information, not the current method information. I use stacktrace for this, which is not in the Reflection namespace.

Can I guarantee that β€œthis” specific information (call method) will be present in the working environment?

var stackTrace = new StackTrace(); return LogManager.GetLogger(stackTrace.GetFrame(1).GetMethod().DeclaringType); 

Hooray!

+6
reflection c #
source share
2 answers

Yes, even in the release build without the PDB, you will have method names in the stack trace. But personally, I would think about this smell of code . This implies a very fragile code path (for example, what happens if you create a WriteLine method that calls the Write method, in which case you are looking at the caller?). It is also not safe to take a snapshot of the stack trace with each call to the log.

I recently posted a question on how to use MEF to insert a registrar into my class, and I wanted to associate the type name with the log data. MEF did a great job because I was able to import an instance of ILogger for each class that wanted to use it, and when the instance of ILogger was imported, I would set its Category property to the name of the current class. No reflection, no stack trace. It worked out fine for me.

+7
source share

Josh is right. Stack tracing is very expensive and should be avoided. It's a little hard to understand what you are doing, but it sounds pretty bad. My first suggestion is to take another look at your production environment and see which logging services already exist and how you can use them.

If you cannot, I would look into already available APIs such as Log4j, SLF4j and Commons to find out how you can use them. Finally, if you are still not using, you can at least look at their source to see how they do it. Also, the source for JUnit analyzes the stack trace, if I remember correctly, so there is another source of ideas.

But my last word will be to make things as simple as possible. Do not go around creating stack traces. Generally speaking, you really only care about them when an exception occurs, and then it is passed to you. You do not need to do anything but pass it on.

+3
source share

All Articles