Search code examples
yamlnlog

NLog config in YAML format


I'm using NLog and want to store its configuration in YAML files instead of XML or JSON.

I have the working code (.NET 6) which works with the below YAML, except for the commented-out part. It uses NetEscapades.Configuration.Yaml library to make YAML magic.

The question is about the "variable" elements which I'm unable to convert into YAML.

NLog:
  throwConfigExceptions: true
  internalLogToConsole: true
  
  # How to write this in YAML?
  #<variable name="var1" value="value1" />
  #<variable name="var2" value="value2" />
  
  targets:
    file:
      type: File
      fileName: someFilename.txt
      layout: layout
  rules:
  - logger: "*"
    minLevel: Trace
    maxLevel: Fatal
    writeTo: file

The C# code that setups logging in case someone is interested in it:

var host =
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(config =>
        {
            config.AddYamlFile(@"nlog.yml", optional: false, reloadOnChange: true);
        })
        .ConfigureServices((host, services) =>
        {
            ConfigurationServices.Register(host.Configuration, services);
        })
        .ConfigureLogging((host, logging) =>
        {
            logging.AddNLog(host.Configuration);
        })
        .Build();

What I tried (and it didn't work):

variable: 
  - 
    name: "var1"
    value: "value1"
  - 
    name: "var2"
    value: "value2"



variable:
  - '@name': var1
    '@value': value1
  - '@name': var2
    '@value': value2



variable:
  - { '@attributes': { name: var1, value: value1 } }
  - { '@attributes': { name: var2, value: value2 } }

Update

Thanks to Rolf Kristensen, this syntax is working:

variables:
  var1: value1
  var2: value2

Solution

  • YAML configuration should work just like JSON configuration, so performing a JSON-to-YAML conversion should produce a working configuration.

    Example with NLog variables:

    NLog:
      throwConfigExceptions: true
      variables:
        LogDirectory: "${basedir}"
      targets:
        logFile:
          type: File
          fileName: ${LogDirectory}/info.log
        logConsole:
          type: Console
      rules:
      - logger: "*"
        minLevel: Trace
        writeTo: logFile
      - logger: "*"
        minLevel: Warn
        writeTo: logConsole
    

    See also: https://github.com/NLog/NLog.Extensions.Logging/issues/446