Azure

Utilizing Azure Utility Insights For Exception Logging In C#

Seek for Utility Insights within the search field.

 

 

Click on on the + New icon button to create a brand new Utility Insights.

 

 

Fill within the following particulars, 

  • Useful resource Group – Use the present one if had already created or create a brand new useful resource group with the identify NetworkWatcherRG.
  • Title – Present the identify as LogsAppInsights. 
  • Area – Choose the specified area.
Using Azure Application Insights for Exception Logging in C#

 

Browse the useful resource group the place you will discover the LogsAppInsights created and click on on the app insights useful resource and duplicate the Instrumentation Key from the highest as proven under,

 

  

Step 2 – Configure the App Insights 

 

On this demo we have been utilizing ASP.NET Core 5.Zero software, we’ll want the .Internet 5.0 SDK and Visual Studio 2019 put in in our machine and in addition the newly created Instrumentation Key to be configured on this challenge so Purposes Insights can work.

 

After creating the ASP.NET Core software from Visual Studio.

 

Putting in the required NuGet bundle,

 

 

 

Including the Utility Insights service in Startup.cs File.

  1.   
  2. public void ConfigureServices(IServiceCollection providers)  
  3. {  
  4.   
  5.     providers.AddControllers();  
  6.     providers.AddSwaggerGen(c =>  
  7.     {  
  8.         c.SwaggerDoc(“v1”new OpenApiInfo { Title = “Logs_App_Insights”, Model = “v1” });  
  9.     });  
  10.     providers.AddApplicationInsightsTelemetry();  
  11. }  

Including the Instrumentation key which is an identifier in your software insights useful resource. we are able to move the instrumentation key contained in the service or go away it clean it will use the configuration supplier to acquire the important thing. Let’s outline the important thing within the appsettings.json file.

  1. “ApplicationInsights”: {  
  2.    “InstrumentationKey”“Copy paste the important thing from Azure portal (Utility Insights)”  
  3.  }  

With the above Instrumentation key, now we have configured the Utility Insights into our software.

 

Step 3 – Saving the Logs to Utility Insights

 

To be able to save the logs or exceptions we simply have to make use of the ILogger service that’s configured by default in ASP.NET Core functions and that is achieved by injecting the ILogger service into no matter class we wish. Let’s use the climate controller as a result of it already has the ILogger service injected.

 

Completely different Ranges that Logger accepts

  • LogDebug
  • LogInformation
  • LogWarning
  • LogError
  • LogCritical  

Let’s add these completely different Logs within the GET Endpoint of the Climate controller and after operating the applying we are able to see these logs within the Azure Utility Insights useful resource,

  1. utilizing Microsoft.AspNetCore.Mvc;  
  2. utilizing Microsoft.Extensions.Logging;  
  3. utilizing System;  
  4. utilizing System.Collections.Generic;  
  5. utilizing System.Linq;  
  6. utilizing System.Threading.Duties;  
  7.   
  8. namespace Logs_App_Insights.Controllers  
  9. {  
  10.     [ApiController]  
  11.     [Route(“[controller]”)]  
  12.     public class WeatherForecastController : ControllerBase  
  13.     {  
  14.         personal static readonly string[] Summaries = new[]  
  15.         {  
  16.             “Freezing”“Bracing”“Chilly”“Cool”“Delicate”“Heat”“Balmy”“Scorching”“Sweltering”“Scorching”  
  17.         };  
  18.   
  19.         personal readonly ILogger<WeatherForecastController> _logger;   
  20.   
  21.         public WeatherForecastController(ILogger<WeatherForecastController> logger)   
  22.         {  
  23.             _logger = logger;  
  24.         }  
  25.   
  26.         [HttpGet]  
  27.         public IEnumerable<WeatherForecast> Get()  
  28.         {  
  29.             var iteration = 1;  
  30.             _logger.LogDebug($“Debug {iteration}”);  
  31.             _logger.LogInformation($“Info {iteration}”);  
  32.             _logger.LogWarning($“Warning {iteration}”);  
  33.             _logger.LogError($“Error {iteration}”);  
  34.             _logger.LogCritical($“Vital {iteration}”);  
  35.             attempt  
  36.             {  
  37.                 throw new NotImplementedException();  
  38.             }  
  39.             catch (Exception ex)  
  40.             {  
  41.                 _logger.LogError(ex, ex.Message);  
  42.             }  
  43.             var rng = new Random();  
  44.             return Enumerable.Vary(1, 5).Choose(index => new WeatherForecast  
  45.             {  
  46.                 Date = DateTime.Now.AddDays(index),  
  47.                 TemperatureC = rng.Subsequent(-20, 55),  
  48.                 Abstract = Summaries[rng.Next(Summaries.Length)]  
  49.             })  
  50.             .ToArray();  
  51.         }  
  52.     }  
  53. }  

Logs in Azure  App Insights

 

Click on the LogsAppInsights and within the menu bar, you could find the Logs choice underneath the Monitoring part, click on on the Logs choice it is going to take us to NewQuery the place we are able to see all of the choices.

 

 

On the right-hand facet underneath the Utility insights, we are able to see loads of choices to see the logs with differing kinds.

 

traces 

 

Double click on on the traces (is an object by which our log messages are saved) choice the place it is going to open within the Question window, click on on the Run button to see the output as proven within the under image,

 

 

As I discussed above right here we are able to see the Warning, Error, Vital messages recognized by traces and in addition we are able to write the queries to filter the info by its varieties and now we have an choice to retailer these queries for additional reference.

 

Question – Utility Insights 

 

Right here we’re filtering the traces by “timestamp” descending order and with “Vital” message see the picture under,

 

 

Additionally in the event you see the above picture there are many choices offered by Azure to avoid wasting & share the Question and to export the identical in no matter format we wish.

 

Correlation with HTTP requests

 

One most helpful discipline in that traces is operation_ParentId which lets you have the correlation id that identifies all of the messages that got here from the identical HTTP request on our Net API,

 

 

 

We will see the identical father or mother id’s for all of the traces underneath that HTTP request – API,

 

 

Exceptions

 

We will see the debug and Info exceptions underneath the exception part the place now we have to write down the question to get that end result.

 

We even have an choice to see these exceptions within the Failure sections underneath the Utility Insights. See the under picture,

 

 

 

A degree to say right here by default .Internet core provides us the Log choices like warning, error, and Vital we have to add a bit of code if we wish the Debug and Info logs to be tracked from our challenge.

 

Setup the Configuration – Debug & Info.

 

Add the below-highlighted code within the appsettings.json file to hint these remaining incidents in Azure App insights,

  1. {  
  2.   “Logging”: {  
  3.     “ApplicationInsights”: {  
  4.       “LogLevel”: {  
  5.         “Default”“Debug”,  
  6.         “Microsoft”“Error”  
  7.       }  
  8.     },  
  9.       “LogLevel”: {  
  10.         “Default”“Info”,  
  11.         “Microsoft”“Warning”,  
  12.         “Microsoft.Internet hosting.Lifetime”“Info”  
  13.       }  
  14.     },  
  15.   “AllowedHosts”“*”,  
  16.   “ApplicationInsights”: {  
  17.     “InstrumentationKey”“be3c95df-3610-4acb-8787-3d84186de336”  
  18.   }  
  19. }  

After operating the applying we are able to see the remaining Debug and Info logs within the traces part,

 

 

If you wish to observe Failed requests, Server response time, server requests, and Availability. Click on on the Overview choice on the high of the App insights the place you’ll be able to see the Graphical illustration of all these info.

 

 

 

Conclusion 

 

Hope this text provides you a transparent thought about easy methods to configure the logs with Azure Utility Insights and in addition viewing the logs from the Azure portal with Queries and so forth so forth. Thanks for studying, please let me know your questions, ideas, or suggestions within the feedback part. I respect your suggestions and encouragement.

 

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button