Search code examples
runtimeazure-blob-storageconnection-stringnlog

NLog blob storage extension with dynamic connection string


BlobStorage target property is not changed as I expected.

I use this code. (of course le connection string is the real azureblobstorage one)

LogManager.Configuration.Variables["simple-log-file-name"] = "simple-log.txt";
LogManager.Configuration.Variables["blob-container"] = "logs";
LogManager.Configuration.Variables["blobconst"] = "DefaultEndpointsProtocol=https;AccountName=....";

Target is setup in nlog.config:

<target xsi:type="AzureBlobStorage" name="simple-log-target" blobName="${var:simple-log-file-name}" container="${var:blob-container}" connectionString="${var:blobconst}"....

At this point nlog fail to setup with

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

If I put the Aure connection string in nlog config target, it works: It writes to storage defined by nlog.config in container and blob that are set in runtime.

<target xsi:type="AzureBlobStorage" name="simple-log-target" blobName="${var:simple-log-file-name}" container="${var:blob-container}" connectionString="DefaultEndpointsProtocol=https;AccountName=...." ...

Is it possible to define this connectionString at runtime at all ?


Solution

  • Instead of using NLog-Configuration-Variables then try using GDC:

    GlobalDiagnosticsContext.Set("simple-log-file-name", "simple-log.txt");
    GlobalDiagnosticsContext.Set("blob-container", "logs");
    GlobalDiagnosticsContext.Set("blobconst", "DefaultEndpointsProtocol=https;AccountName=....";
    

    And setup NLog.config like this (Make sure to assign GDC-values before creating first NLog.Logger-object):

    <target xsi:type="AzureBlobStorage" name="simple-log-target" blobName="${gdc:simple-log-file-name}" container="${gdc:blob-container}" connectionString="${gdc:blobconst}"
    

    See also: NLog.Extensions.AzureBlobStorage - Azure ConnectionString