Skip to content
Rolf Kristensen edited this page Aug 26, 2019 · 34 revisions

Loading from appsettings.json

Introduced with NLog.Extensions.Logging ver. 1.5.0

var config = new ConfigurationBuilder()
   .SetBasePath(System.IO.Directory.GetCurrentDirectory())
   .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
   .Build();

LogManager.Configuration = new NLogLoggingConfiguration(config.GetSection("NLog"));

Simple Json NLog Config Example

{
    "NLog": {
        "throwConfigExceptions": true,
        "targets": {
            "logfile": {
                "type": "File",
                "fileName": "c:/temp/nlog-${shortdate}.log"
            },
            "logconsole": {
                "type": "Console"
            }
        },
        "rules": [
            {
                "logger": "*",
                "minLevel": "Info",
                "writeTo": "logconsole"
            },
            {
                "logger": "*",
                "minLevel": "Debug",
                "writeTo": "logfile"
            }
        ]
    }
}

Extended Json NLog Config Example

{
    "Logging": {
        "LogLevel": {
            "Default": "Debug"
        },
        "NLog": {
            "IncludeScopes": true
        }
    },
    "NLog": {
        "autoReload": true,
        "throwConfigExceptions": true,
        "internalLogLevel": "info",
        "internalLogFile": "${basedir}/internal-nlog.txt",
        "extensions": {
            "NLog.Extensions.Logging": {
                "assembly": "NLog.Extensions.Logging"
            }
        },
        "variables": {
            "var_logdir": "c:/temp"
        },
        "default-wrapper": {
            "type": "AsyncWrapper",
            "overflowAction": "Block"
        },
        "targets": {
            "all-file": {
                "type": "File",
                "fileName": "${var_logdir}/nlog-all-${shortdate}.log",
                "layout": {
                    "type": "JsonLayout",
                    "Attributes": [
                        { "name": "timestamp", "layout": "${date:format=o}" },
                        { "name": "level", "layout": "${level}" },
                        { "name": "logger", "layout": "${logger}" },
                        { "name": "message", "layout": "${message:raw=true}" },
                        { "name": "properties", "encode": false, "layout": { "type": "JsonLayout", "includeallproperties": "true" } }
                    ]
                }
            },
            "own-console": {
                "type": "LimitingWrapper",
                "interval": "00:00:01",
                "messageLimit": 100,
                "target": {
                    "type": "Console",
                    "layout": "${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|${callsite}"
                }
            }
        },
        "rules": [
            {
                "logger": "*",
                "minLevel": "Trace",
                "writeTo": "all-file"
            },
            {
                "logger": "Microsoft.*",
                "maxLevel": "Info",
                "final": true
            },
            {
                "logger": "*",
                "minLevel": "Debug",
                "writeTo": "own-console",
                "filters": {
                    "whenRepeated": {
                        "layout": "${message}",
                        "action": "Ignore"
                    }
                }
            }
        ]
    }
}

Environment specific configuration

ASP.NET Core uses the environment variable ASPNETCORE_ENVIRONMENT to configures app behavior based on the runtime environment. It also allows one to override appsettings for an environment:

  • appsettings.json - Default settings
  • appsettings.Production.json - Production specific settings.
  • appsettings.Development.json - Development specific settings.

This can also be used for the NLog-config, so one can have special NLog targets for a certain environment

It is also possible to adjust environment variables using launchsettings.json. Ex: "environmentVariables": { "NLOG_RULES_0_MINLEVEL": "Info" }

SplitGroup Target Wrapper

The SplitGroup-target-wrapper can be used to introduce extra NLog-target output without changing logging-rules.

Logging Rule Override

Example of how one can override logging-rule "0" and introduce an additional logging-rule.

Note one can also use more readable names instead of "0". Ex. call them "00_ErrorLog", "01_DebugFile". It is important to keep the numeric-prefix because the order of NLog Logging Rules is important (Ex. final-rules).

appsettings.json

        "rules": {
            "0": {
                "logger": "*",
                "minLevel": "Error",
                "writeTo": "errorFile,errorEmail"
            },
            "1": {
                "logger": "*",
                "minLevel": "Debug",
                "writeTo": "debugFile"
            }
        }

appsettings.development.json

        "rules": {
            "0": {
                "logger": "*",
                "minLevel": "Error",
                "writeTo": "errorFile"
            },
            "2": {
                "logger": "*",
                "minLevel": "Debug",
                "writeTo": "debugConsole"
            }
        }

Case Sensitivity Issues in override:

While the ASP.NET Core configuration system is not case sensitive, you must be aware that in some cases NLog is case sensitive. For example, if you wanted to use an environment variable to override the var_logdir NLog variable in the configuration example above, you might be tempted to name the environment variable NLOG__VARIABLES__VAR_LOGDIR. This variable will result in an NLog configuration error, because NLog is looking for a variable named var_logdir. In order to work, your environment variable would need to be named NLOG__VARIABLES__var_logdir.

Clone this wiki locally