Search code examples
.net-corenlog.net-7.0

NLog extension in dotnet core without nlog.config


I'm using NLog in a ASP.NET Core project, configured in code instead of using a nlog.config file. As described here:

https://github.com/NLog/NLog/wiki/Configure-from-code

I want to use the NLog.Web.AspNetCore extension, but can't find a way of using it when configuring in code. All examples I've see involve using a nlog.config, add adding this in the XML:

<extensions>
    <add assembly="NLog.Web.AspNetCore"/>
</extensions>

My code to do the config is this..

var config = new LoggingConfiguration();

// add rules, targets is working fine...

var dbTarget = new DatabaseTarget();
// ... database config - removed
config.AddTarget("database", dbTarget);

var dbRule = new LoggingRule("*", loggingSettings.LogLevel, dbTarget);
config.LoggingRules.Add(dbRule);

LogManager.Configuration = config;

I want something like this, but no luck:

config.AddExtention("NLog.Web.AspNetCore")

Solution

  • You can use NLog Fluent Config like this with NLog v5:

    NLog.LogManager.Setup()
        .SetupExtensions(e => e.RegisterNLogWeb())
        .LoadConfiguration(c => {
           c.ForLogger().FilterMinLevel(loggingSettings.LogLevel).WriteTo(dbTarget);
        });