30

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?

Community
  • 1
  • 1
dferraro
  • 6,357
  • 11
  • 46
  • 69
  • 3
    Have you checked the [`${callsite}` layout renderer](https://github.com/nlog/nlog/wiki/Callsite-Layout-Renderer) ? – nemesv Feb 22 '14 at 08:42
  • that was it - could you answer this question with that solution so I could give you proper credit? thanks – dferraro Feb 24 '14 at 19:12

1 Answers1

64

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>
fractor
  • 1,534
  • 2
  • 15
  • 30
nemesv
  • 138,284
  • 16
  • 416
  • 359