NLog / NLog.Web

NLog integration for ASP.NET & ASP.NET Core 2-8
https://nlog-project.org
BSD 3-Clause "New" or "Revised" License
319 stars 166 forks source link

aspnet-request vars are empty in ASPNET Core 3.1 API #584

Closed jchapmantcg closed 4 years ago

jchapmantcg commented 4 years ago

Type: Question/Bug

NLog version: 4.7.2

NLog.Web.AspNetCore version: 4.9.2

NLog.Extensions.Logging version: N/A

Platform: .NET Core 3.1

Current NLog config (xml or C#, if relevant)


// Console
config.AddTarget(new ConsoleTarget("logconsole"));

// Papertrail
var paperTrail = new SyslogTarget();
paperTrail.Name = "PaperTrail";
paperTrail.MessageCreation.Facility = NLog.Targets.Syslog.Settings.Facility.Local7;
paperTrail.MessageCreation.Rfc5424.AppName = "TESTAPP";
paperTrail.MessageSend.Protocol = NLog.Targets.Syslog.Settings.ProtocolType.Tcp;
paperTrail.MessageSend.Tcp.Server = "xxxxxxx";
paperTrail.MessageSend.Tcp.Port = xxxxxx;
paperTrail.MessageSend.Tcp.Tls = new NLog.Targets.Syslog.Settings.TlsConfig { Enabled = true };
paperTrail.Layout = "${uppercase:${level}}|${aspnet-Request-Method}|${aspnet-request-url:IncludeQueryString=true}|${message}|${exception:format=tostring}";
config.AddTarget(paperTrail);

config.AddRuleForAllLevels("PaperTrail");

_logger = NLogBuilder.ConfigureNLog(config).GetCurrentClassLogger();

In case of a BUG:

snakefoot commented 4 years ago

When #540 is merged and released, then things will get easier.

But while waiting for that, then I guess the following clumsy work-around can be used:

/* Register NLog.Web Extensions */
var dummy = LogginConfiguration();
NLogBuilder.ConfigureNLog(dummy);

/* Setup the actual confg, now has access to NLog.Web Extensions */

_logger = NLogBuilder.ConfigureNLog(config).GetCurrentClassLogger();
jchapmantcg commented 4 years ago

@snakefoot This produced the same results.

snakefoot commented 4 years ago

@jchapmantcg The ${aspnet-Request} requires two things:

You can setup the service-locator using AddNLog or UseNLog.

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
      .ConfigureWebHostDefaults(webBuilder =>
      {
          webBuilder.UseStartup<Startup>();
      })
      .ConfigureLogging(logging =>
      {
          logging.ClearProviders();
          logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
      })
      .UseNLog();  // NLog: Setup NLog for Dependency injection (Make ${aspnet-Request} work)

See also: https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3

jchapmantcg commented 4 years ago

This is what I was missing! Thanks @snakefoot