Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the StackTrace Class in a production environment to get calling method info

We have a "log" class which uses Relection.MethodBase to send current class info to the log.

The reflection.MethodBase stuff happens in the class itself.

However, I'd like to move that stuff to a single external "log" singleton type class.

In this scenario the external log class needs to get the CALLING info, not the current method info. I'm using stacktrace to do this, which isn't in the Reflection namespace.

Can I guarantee that "that" specific information (calling method) will be there in a production environment?

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

cheers!

like image 569
andy Avatar asked Apr 29 '10 03:04

andy


1 Answers

Yes, even in a "release" build without any PDB's you will have the method names in a stack trace. But personally I would consider this a code smell. It implies a very fragile code path (for example what happens if you make a WriteLine method that calls a Write method, do you look at the caller's caller in that case?). It also is probably not cheap to take a snapshot of the stack trace on every logging call.

I recently posted a question about using MEF to inject a logger into my class and I wanted to associate a type name with the log data as well. MEF worked out pretty well for me as I was able to import an ILogger instance for each class that wanted to use it and when the ILogger instance was imported, I would set its Category property to the name of the current class. No reflection, no stack trace. It worked pretty nicely for me.

like image 68
Josh Avatar answered Oct 06 '22 01:10

Josh