如何通过 Azure Functions 在本地使用 Application Insights? [英] How can I use Application Insights locally with Azure Functions?

查看:18
本文介绍了如何通过 Azure Functions 在本地使用 Application Insights?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ILogger 接口在我的 Azure 函数中记录事件.我可以在 Azure 中发布它并将其连接到 Azure 中的 Application Insights.

我想在开发期间在 Visual Studio 的 Application Insights 中查看我的日志.在

I'm using the interface ILogger to log events inside my Azure functions. I can publish it in Azure and connect it to Application Insights in Azure.

I want to see my logs inside Application Insights in my Visual Studio during development. In here I can see this is possible in a ASP.NET Core Web Application putting some code in Startup.cs. Is something similar possible with Azure Functions using the new project template from the tooling in VS 2017?

I'm using VS 2017 and Azure Function CLI 1.0.0-beta-100.

解决方案

As far as I know, currently we couldn't directly include the Application Insights in your local azure function project.

Here is a workaround:

You need implement it by yourself. After installed the Microsoft.ApplicationInsights from the Nuget package manager.

Then use TelemetryClient to send the logs to the azure.

More details, you could refer to below codes:

[FunctionName("HttpTriggerCSharp")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
    var appInsights = GetTelemetryClient();
    //track an event
    appInsights.TrackEvent("I am starting now. I'm timer triggered");
    // track a numeric value
    appInsights.TrackMetric("Ticks based on current time", DateTime.Now.Ticks);
    // track an exception
    appInsights.TrackException(new Exception($"Random exception at {DateTime.Now}"));

    // send data to azure
    appInsights.Flush();

    log.Info($"C# Timer trigger function executed at: {DateTime.Now}");

    log.Info("C# HTTP trigger function processed a request.");

    // parse query parameter
    string name = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
        .Value;

    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();

    // Set name to query string or body data
    name = name ?? data?.name;

    return name == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}

private static TelemetryClient GetTelemetryClient()
{
    var telemetryClient = new TelemetryClient();
    telemetryClient.InstrumentationKey = "Your InstrumentationKey";
    return telemetryClient;
}

Result:

这篇关于如何通过 Azure Functions 在本地使用 Application Insights?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆