JDetmar / NLog.Extensions.AzureStorage

NLog Target for Azure Storage. Uses NLog batch write to optimize writes to Storage.
MIT License
31 stars 19 forks source link

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

Open paulb2015 opened 2 years ago

paulb2015 commented 2 years ago

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

snakefoot commented 2 years ago

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

fuzzzerd commented 2 years ago

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?

snakefoot commented 1 year ago

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