How to retain callsite information when wrapping NLog

后端 未结 8 2141
感情败类
感情败类 2020-11-29 02:33

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

相关标签:
8条回答
  • 2020-11-29 03:08

    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.

    0 讨论(0)
  • 2020-11-29 03:11
    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).

    0 讨论(0)
提交回复
热议问题