NLog.Extensions.AzureStorage icon indicating copy to clipboard operation
NLog.Extensions.AzureStorage copied to clipboard

appsettings.json nlog connectionstring does not work with dotnet user-secrets

Open paulb2015 opened this issue 3 years ago • 3 comments

If the connection string is configured via dotnet user-secrets, nlog logs the following error in its internal log and is unable to log to blob storage.

Error AzureBlobStorageTarget(Name=blob): Failed to create BlobClient with connectionString=. Exception: System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')

Using appsettings.json (snipped):

"connectionString": "${configsetting:ConnectionStrings.Storage}" "ConnectionStrings": { "Storage": "" }

See https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets

paulb2015 avatar Jul 31 '22 23:07 paulb2015

Yes right now the BlobStorage-Target requires that the ConnectionString (or ServiceUrl) is available when initializing the NLog Configuration.

This means ConnectionString stored in user-secrets must be loaded upfront, before loading NLog Configuration.

Maybe it is easier to use ServiceUrl with Managed Client Identity ?

Or find inspiration here #117 to extract secret, and put into NLog GlobalDiagnosticsContext

snakefoot avatar Aug 01 '22 06:08 snakefoot

I just discovered this issue myself; and I'm wondering is it possible that the same issue would exist for using the Azure App Service Configuration section from the portal?

fuzzzerd avatar Aug 19 '22 15:08 fuzzzerd

There is a convience method available when using NLog.Web.AspNetCore, that makes ${configsetting} work before host-builder:

// Loads appsetting.json and enables ${configsetting}
var logger = LogManager.Setup()
                       .LoadConfigurationFromAppSettings()
                       .GetCurrentClassLogger();

One can also do it manually with NLog v5 ("just" need to inject the secrets into the ConfigurationBuilder):

IConfigurationRoot config = new ConfigurationBuilder()
    .AddJsonFile(path: "AppSettings.json").Build();
var logger = LogManager.Setup()
                       .LoadConfigurationFromSection(config)
                       .GetCurrentClassLogger();

See also: https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer

See also: https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-configuration-with-appsettings.json

snakefoot avatar Mar 29 '23 16:03 snakefoot