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. What is the best approach for this?

1
  • Could you please share your appsettings.json and Program.cs file. Commented Aug 29, 2023 at 7:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.