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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With