Search code examples
.netloggingconfignlogserilog

How to activate logging in runtime without restarting application?


It is possible to activate logging in Serilog or NLog without restart .NET application?

I want to activate logging while the application is running on the customers system to see what's wrong.


Solution

  • One of the main features of NLog is that you could change the config while running the application.

    If you have a nlog.config, you could enable autoreload:

    <nlog autoReload="true">
       ...
    </nlog>
    

    Then the config will be reloaded when you save the changes to the file.

    Example

    For example:

    In the config you could change the globalThreshold or the <rules> while running.

    <?xml version="1.0" encoding="utf-8" ?>
    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          autoReload="true"
          globalThreshold="Debug" >
    
      <!-- the targets to write to -->
      <targets>
        <!-- write logs to file  -->
        <target xsi:type="File" name="file1" fileName="c:\temp\nlog-all-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
    
      </targets>
    
      <!-- rules to map from logger name to target -->
      <rules>
        <logger name="*" minlevel="Trace" writeTo="file1" />
      </rules>
    
    </nlog>
    

    From code

    You could also change the config from code, then check LogManager.Configuration. Please note that this property is null if you haven't a config yet (from code or nlog.config).