There is a video version of this tutorial:
When we deploy an application to production, we probably want to use Logs to have information about the things that happen in the application. Then the question arises, where are we going to store these logs? There are several options, one of them is that you create your own provider, so that you can do with the log messages what you want, for example, save them in your database. Another option is to use Application Insights to save these logs.
Application Insights is an Azure service with which we can monitor our applications. It is not limited to being a simple log repository, it also helps us to perform performance analysis of our applications, and includes analytics to help us explore the status of our applications. In this post we will focus on using Application Insights to save and review Logs.
In this entry we will focus on the Back-End of an ASP.NET Core application, however, we can use Application Insights in other places, such as an Angular, React, NodeJS application, among others.
The application we’ll use is the default application that we obtain when creating an ASP.NET Core 3.1 project with the Web API template. Although everything we do here is valid for any ASP.NET Core project.
If you use Visual Studio, it is quite simple to configure your project to use Application Insights, you just have to:
- Right click on the ASP.NET Core project
- Go to Add> Application Insights Telemetry
- Follow the steps of the Wizard (you need an account in Azure)
If you do not use Visual Studio, or if you want to do the configuration manually, there is no problem:
- Install the Microsoft.ApplicationInsights.AspNetCore package
- In the Startup class, in the ConfigureServices method, add the following line of code services.AddApplicationInsightsTelemetry();
- Finally, you need an instrumentation key that identifies the Azure Application Insights resource to use for your application. To obtain this key go to Azure and create an Application Insights resource. After the resource is created, you will find the Instrumentation Key in the Overview section inside of the Application Insights resource.
- With the key, you must place it in your project. If you don’t want to complicate things, you can pass it as a parameter to the AddApplicationInsightsTelemetry method. Like this services.AddApplicationInsightsTelemetry (“mykey”);. Another option is to use a configuration provider, such as the appSettings.json. Like this:
Then, you can leave the AddApplicationInsightsTelemetry method without parameters.
With this, you have Application Insights configured in your project. You automatically have a log provider to save information in the Application Insights resource.
Saving Logs in Application Insights
In order to save logs in Application Insights just use the ILogger service that is configured by default in ASP.NET Core applications. This is achieved by injecting an ILogger<Class> into the class where you want to perform the Logging, where “Class” is the class in which you are in. Example:
|private readonly ILogger<WeatherForecastController> _logger;|
|public WeatherForecastController(ILogger<WeatherForecastController> logger)|
|_logger = logger;|
With this, you can use the _logger field to log messages.
For example: In the Get method of WeatherForecastController we can do the following:
|public IEnumerable<WeatherForecast> Get()|
|var iteracion = 1;|
|throw new NotImplementedException();|
|var rng = new Random();|
|return Enumerable.Range(1, 5).Select(index => new WeatherForecast|
|Date = DateTime.Now.AddDays(index),|
|TemperatureC = rng.Next(–20, 55),|
|Summary = Summaries[rng.Next(Summaries.Length)]|
As you can see, we are saving messages of type Debug, Information, Warning, Error and Critical. By default, our application will only display Warning, Error and Critical messages on Application Insights, however, we can configure our project to display Debug and Information messages, as we will see later.
If we run the application and visit the previous endpoint, then the log messages will be saved in Application Insights:
Note: these messages can take up to 5 minutes to appear in Application Insights
To see our logs, we must go to our Application Insights > Logs, and we must run a query to the traces object (just write traces in the queries section and press the Run button).
If you look at the previous image, we don’t have the exception. This is because we must look for them in the exceptions object. Clear traces and write exceptions, and press the Run button, and you will get the exception.
If you want to explore exceptions more comfortably, you can use the Failures section on the left in the Azure portal.
As we could see, in the Azure portal we do not get the Debug or Information messages, by default we only send the Warning, Error and Critical messages. To send Debug and Information messages, we can go to the appsettings and place the following:
As you can see, we are saying that the ApplicationInsights logging configuration is going to be Debug. With this, if we rerun the code of our WeatherForecastController, the messages of Debug and Information will be displayed in Azure.
Omit Logs in Development
You probably do not want the logs generated at development time to be displayed on your Azure portal, you want only those from your production server to be displayed. One way to do this is to use different instrumentation keys for development and production, for example, using appsettings.
In the appsettings.Development.json file you can place the following:
And with this, when you are in development, you will use this key which does not point to an Application Insights resource. Then, in production, the instrumentation key placed in the appsettings.json file will be used.
Another idea that you can implement is to place the instrumentation key in an environment variable on the production server. In this way, you do not have the key in code, thus preventing someone without permission from seeing it.
- We can use Logs with Application Insights to know what happens within our applications published in production
- With appsettings we can easily configure our application to only save logs when we are in production and not in development
If you wish to learn about Blazor and ASP.NET Core, consider getting my Udemy course today!