How to retain callsite information when wrapping NLog

后端 未结 8 2160
感情败类
感情败类 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: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).

提交回复
热议问题