Skip to content

Combine XML config with C# config

Rolf Kristensen edited this page May 31, 2023 · 3 revisions

Combining XML config with C# config is tricky, as autoreload/load of the XML file could overwrite the C# config.

To combine both, the ConfigurationChanged event is needed

Example

  • We use the nlog.config and
  • We add the console target and rules in C#
using System;
using NLog;
using NLog.Config;
using NLog.Targets;

class Program
{
    // Define a static logger variable so that it references the logger instanced named "Scribe"
    private static readonly Logger log = LogManager.GetCurrentClassLogger();

    static void Main(string[] args)
    {
        ExtendNLogConfig();

        LogManager.ConfigurationChanged += LogManager_ConfigurationChanged;

        log.Info("Entering Application.");

        Console.WriteLine("Press any key to exit ...");
        Console.Read();
    }


    private static void LogManager_ConfigurationChanged(object sender, LoggingConfigurationChangedEventArgs e)
    {
        if (e.ActivatedConfiguration != null)
        {
           ExtendNLogConfig();
        }
    }

    /// <summary>
    /// Extend the logging rules in the nlog.config with programmically rules.
    /// </summary>
    private static void ExtendNLogConfig()
    {
        // Do NOT set LogManager.Configuration because that will cause recursion and stackoverflow
        var consoleTarget = new ColoredConsoleTarget();
        consoleTarget.Name = "console";
        LogManager.Configuration.AddTarget("console", consoleTarget);

        consoleTarget.Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message} ${exception} ${event-properties:item=MyValue}";
        var rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget);
        LogManager.Configuration.LoggingRules.Add(rule1);
        LogManager.ReconfigExistingLoggers();
    }
}
Clone this wiki locally