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

Viewed 43

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.

1 Answers

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);
    }

}
Related