以编程方式设置NLog目标属性

时间:2016-05-04 02:33:03

标签: c# nlog

我正在使用NLog Azure Storage Logger。我的配置如下, 我不想将存储密钥放在目标中。相反,我将从应用程序设置中使用它,以便我可以在部署环境中将Azure网站设置为“应用程序设置”。如何以编程方式为此目标设置connectionString

 <nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"
   xmlns="http://www.nlog-project.org/schemas/NLog.xsd">

<target type="AzureAppendBlob"
           name="azure"
           layout="${longdate} ${level:uppercase=true} - ${message}"
           connectionString="DefaultEndpointsProtocol=https;AccountName=mylogs;AccountKey=xxxoxxx=="
           container="myappcontainer"
           blobName="${date:format=yyyy-MM-dd}.log" />

          

寻找类似的东西,

public class NLogService: IMyLogService
{
   ....

    public NLogService()
    {
        Logger azureLogger = LogManager.GetLogger("AzureAppendBlob");
        AzureAppendBlobTarget t = dbLogger.????;
        t.ConnectionString = "..."; 
    }
}

2 个答案:

答案 0 :(得分:1)

推荐方式:

var azureBlobTarget = LogManager.Configuration.FindTargetByName<AzureAppendBlobTarget>("azure");
azureBlobTarget.ConnectionString = "DefaultEndpointsProtocol=https;AccountName=mylogs;AccountKey=xxx";

如果NLog配置了xml文件,这也有效。

答案 1 :(得分:0)

想出怎么做,

    public NLogService()
    {
        var config = new LoggingConfiguration();
        var azureBlobTarget = new AzureAppendBlobTarget();
        config.AddTarget("azureAppender", azureBlobTarget);

        azureBlobTarget.BlobName = "${date:format=yyyy-MM-dd}.log";  
        azureBlobTarget.ConnectionString = "DefaultEndpointsProtocol=https;AccountName=mylogs;AccountKey=xxx";
        azureBlobTarget.Container = "myapp";
        azureBlobTarget.Layout = @"${longdate} ${level:uppercase=true} - ${message}";            

        var rule1 = new LoggingRule("*", LogLevel.Debug, azureBlobTarget);
        config.LoggingRules.Add(rule1);

        // Step 5. Activate the configuration
        LogManager.Configuration = config;
    }