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.