I'm using NLog for logging, I use a wrapper to call log methods, my problem is: if I try to print information about the call site (${callsite}
), it prints the wrapper method and not the original method that caused the logger to log.
Is there any way to get the original method that called the wrapper method instead?
You could also add this to your NLogLogger Class and call it in the first line of the Write method.
See my answer to this question:
Problem matching specific NLog logger name
I have copied the example code (for an abbreviated NLog wrapper) from that answer here to save some trouble:
Note that this answer was given in the context of NInject. The same principal applies to wrapping NLog even if you are not using NInject. The key is communicating to NLog the type of your wrapper.
This is on example of how to write an NLog wrapper correctly (i.e. to maintain call site info). The key is in the Write method. Notice how it uses NLog's Log method. Notice also that is passes the type of the wrapper class as the first parameter. NLog uses the type information to navigate up the call stack. As soon as it sees a method whose DeclaringType is the passed-in type (i.e. the type of the wrapper), it knows that the next frame up the stack is the calling method.
Also see this link (to NLog's source repository) for two more examples of "extending" Logger. One by wrapping, one by inheriting:
https://github.com/jkowalski/NLog/tree/master/examples/ExtendingLoggers
I am not 100% sure, but I think that you cannot simply wrap NLog and delegate the Info, Debug, Warn, etc method to NLog like this:
You need a way to tell NLog the type of your wrapper and I think that you can only do that by calling NLog via the Logger.Log method (overloaded).
If this is not useful enough, post your wrapper for more help.
Guys After several days hard work and search.Finally, I just use one simple class built the Nlog Wrapper which can retain the ${callsite} and get the correct logger name when created the instance of Nlog Wrapper. I will put the code as followed with simple comment. As you can see I use Stacktrace to get the right logger name. Use write and writewithex to register the logevnet so that can retain callsite. If you have any questions please let me know.