Emitting logs

To write log entries to a log store, such as Application Insights, from an ASP.NET application, two things must be done:

  1. Log entries need to be emitted from application code, where applicable, using the ILogger interface. This interface is available from the Microsoft.Extensions.Logging.Abstractions NuGet package.
  2. The Application Insights NuGet package (Microsoft.ApplicationInsights.AspNetCore) needs to be installed and Application Insights needs to be registered as LoggingProvider. This way, all logs sent to the preceding interface are forwarded to the Application Insights code. In turn, this code forwards all the logs to the Application Insights service.

The following example code shows you how to use the ILogger interface from a class to emit a structured log entry:

public class Example
{
private readonly ILogger<Example> _logger;

public Example(ILogger<Example> logger)
{
_logger = logger;
}

public void DoSomething(User user)
{
_logger.LogWarning(
"Doing something for user with id '{userId}' and username '{username}'",
user.Id,
user.Username);
}
}
There should be no dollar sign ($) at the start of the log entry. There is no string interpolation used here, but two placeholders are inserted into the text message. The structured logging entry will recognize these and when showing the entry, insert the provided values.

With log entries emitted, a logging provider should be registered to capture these logs. This is done using the .NET Core built-in dependency injection.

After installing the Application Insights NuGet package, the following code needs to be added to the CreateWebHostBuilder method:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) 
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(builder => {
builder.AddApplicationInsights(“myKey”);
}
}

When using version 2.7.0-beta3 (or later) of the Application Insights NuGet package and using Application Insights for metrics, the preceding configuration is no longer needed.

After starting the application, all log entries of level warning and higher are automatically forwarded to Application Insights. To change which entries are forwarded and which aren't, filters can be configured. A link to more details on configuring Application Insights in detail is provided at the end of this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset