datalust/nlog-targets-seq

Cant get Seq target to work with $configsetting

SirGordon opened this issue · 5 comments

Hello,
This example https://github.com/304NotModified/NLog-Demo-cases/tree/master/AspNetCore2WithConfigSetting
works fine unitl I try to add a Seq target with a ${configsetting}

To reproduce:

  1. Add Target.Register<SeqTarget>("Seq"); as first line in Program.cs
  2. Change second target in nlog.config to:
<target xsi:type="Seq" name="ownFile-web" serverUrl="${configsetting:name=serverUrl}">
  <property name="Source" value="Seq Target Test"/>
</target>
  1. Add "serverUrl": "http://webtest4:5341/" to appsettings.json
  2. Add <PackageReference Include="NLog.Targets.Seq" Version="1.2.0-dev-00075" /> to csproj

internal log:

Error Seq Target[ownFile-web]: Error initializing target Exception: System.UriFormatException: Invalid URI: The format of the URI could not be determined.

Am I doing something wrong?

NLog is having a hard time with dependency injection and lazy initialization. Trying to improve on this in NLog 5.0 but until then you have to help out yourself.

Manual load configuration before loading NLog.config:

var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    .AddEnvironmentVariables();

Configuration = builder.Build();

NLog.Extensions.Logging.ConfigSettingLayoutRenderer.DefaultConfiguration = Configuration;

// Now we are ready to load the NLog-config
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

Another solution is to remove all code related to NLog. So remove call to NLogBuilder and remove any creation of NLog Logger-objects until having called AddNLog() or UseNLog()

See also: NLog/NLog.Extensions.Logging#265

Guess some magic could be sprinkled into this class, so delay the rendering of URL until start writing LogEvents.

This would have the side-effect that wrong configured SeqTarget would only be discovered when starting logging, instead of at startup.

Thanks for your advice, @snakefoot. I think, if possible, we should stick to standard NLog initialization (avoid sprinkling magic) in order to keep the sink better aligned with the rest of the NLog ecosystem, especially given the workarounds you mentioned.

@SirGordon please let us know if you're still blocked after trying the options above. Thanks for dropping by!

Thank you very much for quick responses, both ways work fine.

NLog.Web.AspNetCore ver 4.9.3 has been released, and now you can do this:

var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();

That replaces the old style:

var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();