0

I'm new to minimal api net7 .I want to log the application insights when any exception raise and read the configuration from app.settings.json in another common library. here i'm using the concept of endpoints to segregate the minimal api net7.

here is the example

public class RegisterEndpoint : IEndpoint
 {
  public void RegisterEndpoints(WebApplication app)
    {
         var apiRoute = app.MapGroup("api/register");
          apiRoute.MapGet("user", User user, IRegisterService _regService) =>
          {
             //check user exists or not
              if(!isUserExists)
              {
                  // register the user in this methos if any exception 
                  //raise log into application insights and if any configuration is required need to send 
                  // how to do that ?
                  // need to send as a parameter app.logger and builder.configuration to every method 
              }
          });

    }
 }

Register service is in another common class library and want to log the application insights and read configuration from app.settings.json. Please suggest me best approach to do.

Thanks everyone in advance!

Harshitha
  • 3,784
  • 2
  • 4
  • 9
prasanthi
  • 562
  • 1
  • 9
  • 25

1 Answers1

0

We can use Dependency Injection to log Application Insights from a common class library.

Install the required NuGet package Microsoft.ApplicationInsights.AspNetCore or add the Application Insights Telemetry from the Connected Services.

enter image description here

Reading configuration in common class library

In the newly created common library, get the Instrumentation Key from appsettings.json file.

My CommonCL.cs file:

using Microsoft.Extensions.Configuration;

public class CommonCL
{
    private readonly IConfiguration myconfig;
    private readonly ILogger<CommonCL> mylog;

    public CommonCL(IConfiguration configuration, ILogger<CommonCL> logger)
    {
        myconfig = configuration;
        mylog = logger;
    }

    public void LogTraces(string mytraces)
    {
        mylog.LogInformation(mytraces);      
    }
    public void LogExceptions(Exception ex)
    {
        mylog.LogError(ex,"Exception occurred.");
    }
    public string? GetInstrumentation(string Instrumentation)
    {
        return myconfig[Instrumentation];
    }
}

In Program.cs, file register the Class Library.

builder.Services.AddSingleton<CommonCL>();

Refer this SO Thread which explains the configuration for Class Library ,MinimalAPI and appsettings configuration for more information.

Harshitha
  • 3,784
  • 2
  • 4
  • 9