Azure application insights for beginner Edit

Murugan Andezuthu Dharmaratnam | 09 May 2021 | 477

In this article, we will look at how to collect application logs, metrics, and distributed traces using azure application insights and how to use application insights in your application.

Azure Monitor

Azure Monitor is an out of the box cloud service offering from Microsoft which helps you to monitor your Azure applications and infrastructure. It helps to increase the performance and availability of your applications and services in the Azure cloud. Since Microsoft Azure is a sophisticated cloud service it is necessary to use Azure monitoring tools to understanding and ensuring the health and performance of the applications running on it. The azure monitor helps you to collect, analyze and act on the telemetry from your cloud and on-premises environments. Azure Monitor can collect data from every layer in the application stack. Azure Monitor helps you maximize the performance and availability of your applications and proactively identify problems in seconds. It helps you to monitor your infrastructure, network & your applications. telemetry data from on-premises and the Azure cloud can be pushed to azure monitor, This data is stored in a log data store that is optimized for cost and performance. Machine learning–driven insights are then used to quickly identify and resolve the problem.

Azure Monitor supports distributed tracing, metric collection & logging. Data from all resources are collected in the azure monitor into either metrics or logs. Metrics are numerical values that describe some aspect of a system at a particular point in time, it supports near realtime scenarios. logs contain data that can be analyzed using a query language, it is used to perform complex analysis on data from a variety of sources. You can use metric explorer to work on metric data and log analytics to work on log data. To visualize the data you can use Dashboards & Workbooks. You can set up alerts on the azure monitor to alert you in case of a problem.

Insights provide a customized monitoring experience for particular Azure services. The different type of insights available are Application Insights, Container insights & VM insights. In this article we will focus on Application Insights

Application Insights

Application Insights is a feature of Azure Monitor that can be used to collect detailed metrics and logs related to the performance and operation of an application. The application can be written in any language or run in any environment. It is an extensible Application Performance Management (APM) service which can be used by developers and DevOps. Application Insights monitors the availability, performance, and usage of your web applications whether they're hosted in the cloud or on-premises. It helps you to diagnose errors. Application Insights is aimed at the development team, to help you understand how your app is performing and how it's being used.

To use application insights you install a small sdk in your application. You can link your application with application azure application insights using a guid key know as the Instrumentation Key which you can get from the overview section of the application insights service from your azure portal. You can instrument not only the web service application, but also any background components, and the JavaScript in the web pages themselves. The application and its components can run anywhere - it doesn't have to be hosted in Azure.

The impact on your app's performance is small. Tracking calls are non-blocking, and are batched and sent in a separate thread.

Application Insights monitors

  • Request rates, response times, and failure rates - Find out which pages are most popular, at what times of day, and where your users are. See which pages perform best. If your response times and failure rates go high when there are more requests, then perhaps you have a resourcing problem.
  • Dependency rates, response times, and failure rates - Find out whether external services are slowing you down.
  • Exceptions - Analyze the aggregated statistics, or pick specific instances and drill into the stack trace and related requests. Both server and browser exceptions are reported.
  • Page views and load performance - reported by your users' browsers.
  • AJAX calls from web pages - rates, response times, and failure rates.
  • User and session counts.
  • Performance counters from your Windows or Linux server machines, such as CPU, memory, and network usage.
  • Host diagnostics from Docker or Azure.
  • Diagnostic trace logs from your app - so that you can correlate trace events with requests.
  • Custom events and metrics that you write yourself in the client or server code, to track business events such as items sold or games won.

good & Bad Traces, and Severity level in Trace logs

Traces are logged by the application & they help to zero in on the problems when something goes wrong with the application. The traces log information which is generally unstructured, but one thing that can be definitively learned from them is their severity level. There are 5 severity levels in application insights they are 0 - Verbose / Debug, 1 - Information, 2 - Warning, 3 - Error & 4 - Critical. An application can send good traces and bad traces, Debug & Information is good traces, Warning, Error & Critical are bad traces.

If you find that Not all log levels are being logged in Application Insights, that's because by default application insight is configured to only receive Warning, Error, Critical, You can make changes in the client application to send all trace levels to the application insights service.

for an asp .net core application you can set the Severity level in your applicatoin.json file.

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },

for a python application you can use the setLevel function in the logging module

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

Python Sample Code

first you need to install the OpenCensus Azure

python -m pip install opencensus-ext-azure

Then run the below sample code. Once you create the Application insights service To get the Instrumentation Key open the application insight you have created from the overview menu copy dashboard you can copy the Instrumentation Key

import logging
from opencensus.ext.azure.log_exporter import AzureLogHandler

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler = AzureLogHandler(connection_string='InstrumentationKey=YOURKEY;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/')
logger.addHandler(handler)

logger.debug("debug")
logger.info("info")
logger.warning("warning")
logger.error("error")
logger.critical("critical")

.Net Core Sample Code

Getting the application insights to work from your asp .net core application is very easy. Just follow the below instructions.

Step1: go to nuget package manager and install Microsoft.ApplicationInsights.AspNetCore

Step2: Modify the application.json file and add
  "ApplicationInsights": {
    "InstrumentationKey": "YOURKEY-a2ba-ec098fbc3c77"
  }

Step3:

Step4: Inject the ILogger through the constructor

private readonly ILogger _logger;
        
public YourControllerNameController(ILogger logger)
{
            // Hello world
            _logger = logger;
}

Step5: do the logging

_logger.LogDebug("debug");
_logger.LogInformation("info");
_logger.LogWarning("warning");
_logger.LogError("error");
_logger.LogCritical("critical");