I have a class that wraps NLog (called NLogger). My logs are saved to my database. The thing I\'m having a problem with is how do I show where the logging occured. I have th
Nowadays a more simple approach to fix the callsite, is to use LogManager.AddHiddenAssembly(Assembly)
e.g.
LogManager.AddHiddenAssembly(yourAssembly);
This will fix the callsite and no need to do manual stack walking etc.
internal string GetCallingMethodName()
{
string result = "unknown";
StackTrace trace = new StackTrace(false);
for (int i = 0; i < trace.FrameCount; i++)
{
StackFrame frame = trace.GetFrame(i);
MethodBase method = frame.GetMethod();
Type dt = method.DeclaringType;
if (!typeof(ILogger).IsAssignableFrom(dt) && method.DeclaringType.Namespace != "DiagnosticsLibrary")
{
result = string.Concat(method.DeclaringType.FullName, ".", method.Name);
break;
}
}
return result;
}
Source : http://slf.codeplex.com/discussions/210075
I used the posted code above to simply extract the calling method name and pass that as part of the "message" parameter to the layout. This lets me have the original method name where the log wrapper was called be written to the log file (rather than the log wrapper's class name).