Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding method name in NLog

Tags:

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?

like image 624
dferraro Avatar asked Feb 22 '14 03:02

dferraro


People also ask

What can be configured with this NLog config file?

The following types can be configured: Targets - the destinations of a logevent, e.g. file, database, console. Layout - the layout e.g. json, csv, plain-text (default) Layout renderers - the template markers, e.g. ${message}, ${exception}, ${date}

What are the NLog levels?

Writing Log Messages With NLog The available methods for logging are (in ascending order): Trace, Debug, Info, Warn, Error, and Fatal. Each of these methods creates a log message with a corresponding log level—an indicator of the message's importance.


1 Answers

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> 
like image 154
nemesv Avatar answered Sep 18 '22 15:09

nemesv