Application Insight logging in Minimal API .netcore

Newbie Dev 156 Reputation points
2021-12-15T07:47:31.833+00:00

Hi,

I am working on minimal APIs and not quite sure how to add App Insights logging.

Could someone please point me to any documentation?

Thanks in advance.

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Jaliya Udagedara 2,836 Reputation points MVP Volunteer Moderator
    2021-12-15T08:37:39.067+00:00

    It should be the same as in ASP.NET Core.

    using Microsoft.Extensions.Logging;
    
    WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
    
    // ConfigureServices
    builder.Services.AddDbContext<EmployeeContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
    
    // Add Application Insights
    builder.Services.AddApplicationInsightsTelemetry();
    
    await using WebApplication app = builder.Build();
    
    // Configure
    if (app.Environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    
    app.MapGet("/employees", async (EmployeeContext dbContext) =>
    {
        app.Logger.LogInformation("Getting employees");
    
        return await dbContext.Employees.ToListAsync();
    });
    
    await app.RunAsync();
    

    You need to add AppInsights Key to appsettings.json


  2. Anonymous
    2021-12-16T02:54:01.06+00:00

    Hi @Newbie Dev

    To add Application Insights telemetry to ASP.NET Core applications,

    First, you need to ensure the Microsoft.ApplicationInsights.AspNetCore NuGet package is installed. If not, you can install it via Nuget.

    Second, register and configure the Application Insights service in the Program.cs file:

    using Microsoft.Extensions.Logging.ApplicationInsights;  
      
    var builder = WebApplication.CreateBuilder(args);  
      
    // Add services to the container.  
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle  
    builder.Services.AddEndpointsApiExplorer();  
    builder.Services.AddSwaggerGen();  
    builder.Services.AddApplicationInsightsTelemetry();  
    builder.Host.ConfigureLogging((context, builder) =>  
    {  
        // Providing an instrumentation key is required if you're using the  
        // standalone Microsoft.Extensions.Logging.ApplicationInsights package,  
        // or when you need to capture logs during application startup, such as  
        // in Program.cs or Startup.cs itself.  
        builder.AddApplicationInsights(  
            context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]);  
      
        // Capture all log-level entries from Program  
        builder.AddFilter<ApplicationInsightsLoggerProvider>(  
            typeof(Program).FullName, LogLevel.Trace);  
      
    });  
    ...  
    

    Finally, in the API controller, you can use the logger as below:

    public class ValuesController : ControllerBase  
    {  
        private readonly ILogger _logger;  
      
        public ValuesController(ILogger<ValuesController> logger)  
        {  
            _logger = logger;  
        }  
      
        [HttpGet]  
        public ActionResult<IEnumerable<string>> Get()  
        {  
            _logger.LogWarning("An example of a Warning trace..");  
            _logger.LogError("An example of an Error level message");  
      
            return new string[] { "value1", "value2" };  
        }  
    }  
    

    More detailed information, see Application Insights logging with .NET.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.