Application Insights logging with .NET - Azure Monitor (2024)

  • Article

In this article, you learn how to capture logs with Application Insights in .NET apps by using the Microsoft.Extensions.Logging.ApplicationInsights provider package. If you use this provider, you can query and analyze your logs by using the Application Insights tools.

Note

The following documentation relies on the Application Insights classic API. The long-term plan for Application Insights is to collect data using OpenTelemetry. For more information, see Enable Azure Monitor OpenTelemetry for .NET, Node.js, Python and Java applications and our OpenTelemetry Roadmap. Migration guidance is available for .NET, Node.js, and Python.

Note

If you want to implement the full range of Application Insights telemetry along with logging, see Configure Application Insights for your ASP.NET websites or Application Insights for ASP.NET Core applications.

Tip

The Microsoft.ApplicationInsights.WorkerService NuGet package, used to enable Application Insights for background services, is out of scope. For more information, see Application Insights for Worker Service apps.

ASP.NET Core applications

To add Application Insights logging to ASP.NET Core applications:

  1. Install the Microsoft.Extensions.Logging.ApplicationInsights.

  2. Add ApplicationInsightsLoggerProvider:

  • .NET 6.0+
  • .NET 5.0
using Microsoft.Extensions.Logging.ApplicationInsights;var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddControllers();// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbucklebuilder.Services.AddEndpointsApiExplorer();builder.Services.AddSwaggerGen();builder.Logging.AddApplicationInsights( configureTelemetryConfiguration: (config) => config.ConnectionString = builder.Configuration.GetConnectionString("APPLICATIONINSIGHTS_CONNECTION_STRING"), configureApplicationInsightsLoggerOptions: (options) => { } );builder.Logging.AddFilter<ApplicationInsightsLoggerProvider>("your-category", LogLevel.Trace);var app = builder.Build();// Configure the HTTP request pipeline.if (app.Environment.IsDevelopment()){ app.UseSwagger(); app.UseSwaggerUI();}app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();

With the NuGet package installed, and the provider being registered with dependency injection, the app is ready to log. With constructor injection, either ILogger or the generic-type alternative ILogger<TCategoryName> is required. When these implementations are resolved, ApplicationInsightsLoggerProvider provides them. Logged messages or exceptions are sent to Application Insights.

Consider the following example controller:

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" }; }}

For more information, see Logging in ASP.NET Core and What Application Insights telemetry type is produced from ILogger logs? Where can I see ILogger logs in Application Insights?.

Console application

To add Application Insights logging to console applications, first install the following NuGet packages:

The following example uses the Microsoft.Extensions.Logging.ApplicationInsights package and demonstrates the default behavior for a console application. The Microsoft.Extensions.Logging.ApplicationInsights package should be used in a console application or whenever you want a bare minimum implementation of Application Insights without the full feature set such as metrics, distributed tracing, sampling, and telemetry initializers.

  • .NET 6.0+
  • .NET 5.0
using Microsoft.ApplicationInsights.Channel;using Microsoft.ApplicationInsights.Extensibility;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using var channel = new InMemoryChannel();try{ IServiceCollection services = new ServiceCollection(); services.Configure<TelemetryConfiguration>(config => config.TelemetryChannel = channel); services.AddLogging(builder => { // Only Application Insights is registered as a logger provider builder.AddApplicationInsights( configureTelemetryConfiguration: (config) => config.ConnectionString = "<YourConnectionString>", configureApplicationInsightsLoggerOptions: (options) => { } ); }); IServiceProvider serviceProvider = services.BuildServiceProvider(); ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>(); logger.LogInformation("Logger is working...");}finally{ // Explicitly call Flush() followed by Delay, as required in console apps. // This ensures that even if the application terminates, telemetry is sent to the back end. channel.Flush(); await Task.Delay(TimeSpan.FromMilliseconds(1000));}

For more information, see What Application Insights telemetry type is produced from ILogger logs? Where can I see ILogger logs in Application Insights?.

Logging scopes

ApplicationInsightsLoggingProvider supports log scopes. Scopes are enabled by default.

If the scope is of type IReadOnlyCollection<KeyValuePair<string,object>>, then each key/value pair in the collection is added to the Application Insights telemetry as custom properties. In the following example, logs are captured as TraceTelemetry and has ("MyKey", "MyValue") in properties.

using (_logger.BeginScope(new Dictionary<string, object> { ["MyKey"] = "MyValue" })){ _logger.LogError("An example of an Error level message");}

If any other type is used as a scope, it's stored under the property Scope in Application Insights telemetry. In the following example, TraceTelemetry has a property called Scope that contains the scope.

 using (_logger.BeginScope("hello scope")) { _logger.LogError("An example of an Error level message"); }

Frequently asked questions

What Application Insights telemetry type is produced from ILogger logs? Where can I see ILogger logs in Application Insights?

ApplicationInsightsLoggerProvider captures ILogger logs and creates TraceTelemetry from them. If an Exception object is passed to the Log method on ILogger, ExceptionTelemetry is created instead of TraceTelemetry.

Viewing ILogger Telemetry

In the Azure Portal:

  1. Go to the Azure Portal and access your Application Insights resource.
  2. Click on the "Logs" section inside Application Insights.
  3. Use Kusto Query Language (KQL) to query ILogger messages, usually stored in the traces table.
    • Example Query: traces | where message contains "YourSearchTerm".
  4. Refine your queries to filter ILogger data by severity, time range, or specific message content.

In Visual Studio (Local Debugger):

  1. Start your application in debug mode within Visual Studio.
  2. Open the "Diagnostic Tools" window while the application runs.
  3. In the "Events" tab, ILogger logs appear along with other telemetry data.
  4. Utilize the search and filter features in the "Diagnostic Tools" window to locate specific ILogger messages.

If you prefer to always send TraceTelemetry, use this snippet:

builder.AddApplicationInsights( options => options.TrackExceptionsAsExceptionTelemetry = false);

Why do some ILogger logs not have the same properties as others?

Application Insights captures and sends ILogger logs by using the same TelemetryConfiguration information that's used for every other telemetry. But there's an exception. By default, TelemetryConfiguration isn't fully set up when you log from Program.cs or Startup.cs. Logs from these places don't have the default configuration, so they aren't running all TelemetryInitializer instances and TelemetryProcessor instances.

I'm using the standalone package Microsoft.Extensions.Logging.ApplicationInsights, and I want to log more custom telemetry manually. How should I do that?

When you use the standalone package, TelemetryClient isn't injected to the dependency injection (DI) container. You need to create a new instance of TelemetryClient and use the same configuration that the logger provider uses, as the following code shows. This requirement ensures that the same configuration is used for all custom telemetry and telemetry from ILogger.

public class MyController : ApiController{ // This TelemetryClient instance can be used to track additional telemetry through the TrackXXX() API. private readonly TelemetryClient _telemetryClient; private readonly ILogger _logger; public MyController(IOptions<TelemetryConfiguration> options, ILogger<MyController> logger) { _telemetryClient = new TelemetryClient(options.Value); _logger = logger; } }

Note

If you use the Microsoft.ApplicationInsights.AspNetCore package to enable Application Insights, modify this code to get TelemetryClient directly in the constructor.

I don't have the SDK installed, and I use the Azure Web Apps extension to enable Application Insights for my ASP.NET Core applications. How do I use the new provider?

The Application Insights extension in Azure Web Apps uses the new provider. You can modify the filtering rules in the appsettings.json file for your application.

Next steps

  • Logging in .NET
  • Logging in ASP.NET Core
  • .NET trace logs in Application Insights
Application Insights logging with .NET - Azure Monitor (2024)
Top Articles
What are Ghost Accounts? – SafeToNet Foundation
​​Should You Increase Your Credit Card Limit
Sound Of Freedom Showtimes Near Governor's Crossing Stadium 14
Body Rubs Austin Texas
1movierulzhd.fun Reviews | scam, legit or safe check | Scamadviser
Tx Rrc Drilling Permit Query
Mawal Gameroom Download
Becky Hudson Free
Hello Alice Business Credit Card Limit Hard Pull
Santa Clara Valley Medical Center Medical Records
Nashville Predators Wiki
Wordle auf Deutsch - Wordle mit Deutschen Wörtern Spielen
Chicken Coop Havelock Nc
Best Fare Finder Avanti
The best TV and film to watch this week - A Very Royal Scandal to Tulsa King
Teacup Yorkie For Sale Up To $400 In South Carolina
Evil Dead Rise Showtimes Near Pelican Cinemas
Glover Park Community Garden
Tips and Walkthrough: Candy Crush Level 9795
Boston Dynamics’ new humanoid moves like no robot you’ve ever seen
A Man Called Otto Showtimes Near Cinemark University Mall
Silky Jet Water Flosser
Victory for Belron® company Carglass® Germany and ATU as European Court of Justice defends a fair and level playing field in the automotive aftermarket
Kroger Feed Login
Inter Miami Vs Fc Dallas Total Sportek
Egusd Lunch Menu
Is Light Raid Hard
What we lost when Craigslist shut down its personals section
Allegheny Clinic Primary Care North
Math Minor Umn
Kattis-Solutions
Desirulez.tv
#scandalous stars | astrognossienne
Pitco Foods San Leandro
Black Adam Showtimes Near Amc Deptford 8
Kvoa Tv Schedule
Gold Nugget at the Golden Nugget
Craigslist Lakeside Az
Is Arnold Swansinger Married
Banana Republic Rewards Login
Jason Brewer Leaving Fox 25
Easy Pigs in a Blanket Recipe - Emmandi's Kitchen
No Boundaries Pants For Men
VDJdb in 2019: database extension, new analysis infrastructure and a T-cell receptor motif compendium
Login
Arcanis Secret Santa
Sams Gas Price San Angelo
Costner-Maloy Funeral Home Obituaries
Unpleasant Realities Nyt
Craigslist Pets Lewiston Idaho
Kenmore Coldspot Model 106 Light Bulb Replacement
Skybird_06
Latest Posts
Article information

Author: Jamar Nader

Last Updated:

Views: 6062

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Jamar Nader

Birthday: 1995-02-28

Address: Apt. 536 6162 Reichel Greens, Port Zackaryside, CT 22682-9804

Phone: +9958384818317

Job: IT Representative

Hobby: Scrapbooking, Hiking, Hunting, Kite flying, Blacksmithing, Video gaming, Foraging

Introduction: My name is Jamar Nader, I am a fine, shiny, colorful, bright, nice, perfect, curious person who loves writing and wants to share my knowledge and understanding with you.