如何在Azure函数中同时使用日志编写器和应用程序见解?

时间:2018-11-19 01:27:03

标签: c# .net azure azure-functions azure-application-insights

我想向ILogger以及应用程序见解发送跟踪和其他事件。

我知道我可以简单地做到这一点:

    [FunctionName ("OnSomethingHttpTriggered")]
    public static async System.Threading.Tasks.Task RunAsync ([QueueTrigger ("myq", Connection = "StorageAccountConnection")] string payload, ILogger log) {
        var telemetry = new TelemetryClient {
        InstrumentationKey = Environment.GetEnvironmentVariable ("APPINSIGHTS_INSTRUMENTATIONKEY")
        };
        log.LogInformation ($"C# Queue trigger function processed: {payload}");
        telemetry.TrackEvent ($"C# Queue trigger function processed: {payload}");

        var isPayloadValidSchema = SchemaValidator.IsValid (payload);
        if (!isPayloadValidSchema) {
            log.LogError ($"This visit is not valid {payload}");
            telemetry.TrackEvent ($"This visit is not valid {payload}");
            return;
        }
    }

但是您可以看到,ILoggerTelemetryClient每次我都需要加倍代码。

如何避免这种重复?

1 个答案:

答案 0 :(得分:1)

我们不需要telemtryclient来发送ILogger的输出,默认情况下,在我们在应用程序设置中设置APPINSIGHTS_INSTRUMENTATIONKEY时,它们将在appear as traces of local.setting.json)。我们使用telemtryclient发送custom telemetry data