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