Search code examples
c#nlog

NLog feature question: can the stack depth be taken into account while writing logs?


I'm quite new at working with NLog., but I have earlier experience working with logfiles/trace files, but previously the logs looked as follows:

<timestamp> ... | main function logging
<timestamp> ... |   sub function logging.1
<timestamp> ... |     subsub function logging.1.1
<timestamp> ... |     subsub function logging.1.2
<timestamp> ... |   sub function logging.2
<timestamp> ... |     subsub function logging.2.1
<timestamp> ... |       subsubsub function logging.2.1.1
...

As you can see, the indenting was done, based on the depth within the callstack.
In NLog technology (NLog.xml file), I have seen a depth attribute, but I believe this is only meant for limiting the amount of logs, based on the callstack depth, I don't see any indentation configuration.

Does NLog have that feature, where indentation is added, based on the callstack depth?


Solution

  • As soon that you start to use Threads or Async-Tasks, then you suddenly have to ignore a lot Microsoft-Specific-StackFrames. Also the indent might suddenly become weird when mixing with other libraries that uses event-handler and calls your code. At the same time the overhead from capturing StackTrace for every LogEvent will give a performance hit.

    An alternative could be to use class-namespaces/inner-classes to provide indenting, that can extracted from NLog ${logger}:

    namespace ApplicationName
    {
        class Program
        {
             static NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        }
    }
    
    namespace ApplicationName.Controllers
    {
        class MyController
        {
             static NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        }
    }
    
    namespace ApplicationName.Models
    {
        class MyModel
        {
             static NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
    
             class InnerLogic
             {
                 static NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
             }
        }
    }
    

    Yet another alternative could be using nested states with NLog ScopeContext, that can provide indent with NLog ${scopeindent}.