سؤال

I am using NLog and following the recommended pattern of having a log declare on each class, for the purpose of being able to track which class/method has written to the log. I do find this very useful to have a bit of a top level 'stack trace' with each log write.

My code used to look like this:

class SomeClass {

  private static readonly Logger logger = LogManager.GetCurrentClassLogger();
     void DoStuff()   {
      logger.Debug("stuff");   }   

}

I recently had the requirement my single project to write to 3 separate log files, and to do this, I added multiple loggers and targets as specified here: https://stackoverflow.com/a/21711838/191206

However, now in my log files, I have lost the class level name. It now just writes the log name that I specified in the NLog.config. I've considered simply adding the method name myself with a call to

System.Reflection.MethodBase.GetCurrentMethod(); // use Name property

or using something else in Reflection like this

However, I'm wondering if NLog has something built into this that I'm missing? The Debug() method I only see the ability to write a string, with parameters & optionally formatted..

Is this built into NLog?

هل كانت مفيدة؟

المحلول

There is a built in layout renderer called ${callsite} that you can use to include the call site information (class name, method name and source information) in your log entries:

<targets>
  <target
    name="task1File"
    xsi:type="File"
    layout="${callsite} - ${message}"
    fileName="${basedir}../Data/debugLog1.txt"
    archiveAboveSize ="5000000"
    maxArchiveFiles="2"/>
  <target
    name="task2File"
    xsi:type="File"
    layout="${callsite} - ${message}"
    fileName="${basedir}../Data/debugLog2.txt"
    archiveAboveSize ="5000000"
    maxArchiveFiles="2"/>
</targets>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top