如何使用 .NET SDK 将诊断设置添加到 azure 服务?

How to add the diagnostic settings to the azure service using .NET SDK?

如何使用 c# 从 asp.net 核心 Web 应用向 Azure 数据工厂添加和配置诊断设置?

您可以使用 azure 管理 sdk。

1.Install 以下nuget包:

Microsoft.Azure.Management.Fluent, version 1.33.0.

Microsoft.Azure.Management.Monitor.Fluent, version 1.33.0.

2.Create 凭据:

如果您有 azure cli installed locally, or you can use azure cli from azure portal directly. Then follow this article 创建凭据。简而言之,键入以下 azure cli 命令:

az ad sp create-for-rbac --sdk-auth

然后你从输出中得到clientIdclientSecrettenantId,请保存这些值。输出如下:

3.Then 使用下面的代码:

        string clientId = "xxx";
        string clientSecret = "xxx";
        string tenantId = "xxx";

        var credentials = SdkContext.AzureCredentialsFactory
                    .FromServicePrincipal(clientId,
                                          clientSecret,
                                          tenantId,
                                          AzureEnvironment.AzureGlobalCloud);

        var azure = Azure
            .Configure()
            .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
            .Authenticate(credentials)
            .WithDefaultSubscription();

        azure.DiagnosticSettings
            .Define("test2")
            //the resource id of your ADF
            .WithResource("subscriptions/xxx/resourcegroups/xxx/providers/Microsoft.DataFactory/factories/your_ADF_name")
            //the resource id of your azure log analytics
            .WithLogAnalytics("subscriptions/xxx/resourcegroups/xxxx/providers/microsoft.operationalinsights/workspaces/your_azure_log_analytics_name")
            .WithLog("ActivityRuns", 7)
            .WithLog("PipelineRuns", 7)
            .WithMetric("AllMetrics", TimeSpan.FromMinutes(5), 0)
            .Create();

这是来自 github 的 sample code

你也可以使用 azure monitor rest api Diagnostic Settings - Create Or Update 来设置它。