Logging the previous method name

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Logging the previous method name

ShadeOfRed
Hello,

I already posted a request to create an appropriate layout renderer for this but maybe not being an overall expert of NLog there might be already a way to obtain the same result. My need is simple: I'd need to log the name of the method that called the one where the logging is being done. The renderer "callsite" does it for the method where the logging is done ... I'd need to travel the call stack back one method more. This need arises because I'd doing my logging also as part of the creation of my own exception class instances, logging in the costructor all exception details. Using callsite in this scenario is of no use. I'd thus need to log the method name that threw the exception. Is there any way of doing this already with NLog apart having myself to navigate the call stack???


S.

Reply | Threaded
Open this post in threaded view
|

Re: Logging the previous method name

Jarek Kowalski
Administrator
That's not possible today with NLog , but fortunately all you need to do is create a new layout renderer based on ${callsite} as described on the website.

LogEventInfo contains all the information that you require. Just use th UserStackFrameNumber and StackTrace properties.

StackFrame previousStackFrame = ev.StackTrace.GetFrame(ev.UserStackFrameNumber + 1);

That should do the trick. Formatting should be easy then.

Jarek
NLog Blog