简体   繁体   中英

How to create a static instance of TelemetryClient for application insights logging in Azure Functions

I am trying to implement appinsights logging in my application and I cannot create an instance of TelemetryClient as it is deprecated in .net core apps. Now I am using below method to log data in azure functions.

startup.cs file

public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddApplicationInsightsTelemetry();
        }
    }

In my Function.cs file:

public class Function1
    {

        TelemetryClient _telemetry;
        
        public Function1(TelemetryClient telemetry)
        {
            _telemetry = telemetry;
        }

        [FunctionName("Function1")]
        public  async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
        {
            
            // APPINSIGHTS LOG! 
            _telemetry.TrackTrace("Testing the appinsights");
            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = "This HTTP triggered function executed successfully.";
            return new OkObjectResult(responseMessage);
        }
    }

Using the telemetry like above works without any issues. My question is now that how to use this telemetry object across all over my application so that I can access all the telemetry method without creating multiple instances. In the past I used to create a singleton instance of TelemetryClient and use it across application.

For example, I am using the telemetry object in constructor in another class to log some data.

Student.cs file:

using Microsoft.ApplicationInsights;
private TelemetryClient _telemetryClient;

public Student(TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }

Inside the method, I am using it like

_telemetryClient.TrackEvent("We are in SQL Server -> Student.cs File");

Do I need to pass this object in constructor in all the class files I need to log or is there any better way to implement this functionality.

I am new to dependency injection and .net core. Please assist.

Why don't you use the new method - the ILogger? You can have it injected into each and every function (as shown in your code sample), and then use it to log the events to App Insights. ILogger is easy to use as shown below:

[FunctionName("GetVersion")]
public static async Task<IActionResult> GetVersion(
   [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "instance/version")] HttpRequest req,
   ILogger log, ExecutionContext context)
{
    ServerlessVersionModel ver = new ServerlessVersionModel();
    log.LogInformation("[{funcname}] request made", context.FunctionName);
    try
    {
        ver = GetVersions(context,log);
        return new JsonResult(ver);
    }
    catch (Exception e)
    {
        log.LogError("[{funcname}] exception: {exception}.", context.FunctionName, e.Message);
        return new JsonResult(ver);
    }

}

I tried for a day to implement what you are describing. The problem is not to log to application insights. That is happening. If you inject a logger in startup.cs and use it in your Azure function, then go to the Application Insights and do a search for a text term that you logged in your program you will see it. The problem is that you would like to see it appear in the monitor log.

The APPINSIGHTS_INSTRUMENTATIONKEY is deprecated. MS says not to use it. OK. They suggest you use APPLICATIONINSIGHTS_CONNECTION_STRING instead. Here is the problem. If you look at this connection string it has some inte.net urls. These urls are not the same as the one that the ILogger log that is injected into the main Azure function (Run) uses. The urls that MS provides when they create the APPLICATIONINSIGHTS_CONNECTION_STRING are not the same as urls the normal ILogger log uses. Go to application insights and look at the details of two logs: one made with the default logger and one with your logger from startup.cs Two completely different locations in completely different countries (data centers).

So if you want the logs to appear in the monitor log in the Azure function on the portal I suppose you'll need to figure out the connection string that the ILogger log in Run uses. Go figure!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM