Take advantage of Application Insights to monitor performance and detect and diagnose performance issues in your web application. Credit: Thinkstock Azure Application Insights is an extensible application performance management (APM) service that can be used to monitor performance, detect anomalies, and diagnose performance issues for a web application in real time. If you are using .NET Core, you can use Application Insights on the multiple platforms that .NET Core supports (Windows, Linux, or Mac). Note that you can use Application Insights for applications built in various technologies including .NET, JavaScript, Node.js, and Java as well as .NET Core. And you can use Application Insights for such applications whether or not they are hosted in the cloud. In this article we’ll examine how you can log data to Azure Application Insights in an ASP.NET Core application. To work with the code examples illustrated in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here. You will also need an Azure account as we’ll be pushing the log messages to Application Insights in Azure. If you don’t have an Azure account, you can create a free Azure account here. In the sections that follow, we’ll examine how we can configure Application Insights as one of the sinks for the default logger in ASP.NET Core. Create an ASP.NET Core API project First off, let’s create an ASP.NET Core project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Click Create. In the “Create New ASP.NET Core Web Application” window, select .NET Core as the runtime and choose ASP.NET Core 2.2 (or later) from the drop-down list at the top. Select “API” as the project template to create a new ASP.NET Core API application. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that Authentication is set to “No Authentication” as we won’t be using authentication either. Click Create. This will create a new ASP.NET Core API project in Visual Studio. We’ll use this project in the subsequent sections of this article. Install the NuGet packages for Application Insights Now that we have created an ASP.NET Core API project in Visual Studio, the next thing you should do is install the necessary NuGet packages. To do this, select the project in the Solution Explorer window, then right-click and select “Manage NuGet Packages…”. Then install the following packages from the NuGet Package Manager: Microsoft.ApplicationInsights.AspNetCore Microsoft.Extensions.Logging.ApplicationInsights Alternatively, you can install these packages from the NuGet Package Manager Console by entering the following commands: Install-Package Microsoft.ApplicationInsights.AspNetCore Install-Package Microsoft.Extensions.Logging.ApplicationInsights In the next section, we’ll set up our application’s connection to Application Insights. You will need an Azure account to proceed to the next step. Configure logging to Application Insights in AppSettings.json We will need an instrumentation key to connect to Application Insight in Azure and log data. We’ll specify this in the AppSettings.json file. Here is what the contents of the AppSettings.json file will look like: { "Logging": { "LogLevel": { "Default": "Information" }, "ApplicationInsights": { "InstrumentationKey": "Write your instrumentation key here" } }, "AllowedHosts": "*" } Configure logging to Application Insights in the Program class The next step is to configure logging in the Program class in the Program.cs file. The following code snippet shows how this can be achieved. public class Program { public static void Main(string[] args) { CreateWebHostBuilderForApplicationInsights(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilderForApplicationInsights(string[] args) { var webHostBuilder = WebHost.CreateDefaultBuilder(args); webHostBuilder.UseStartup<Startup>() .ConfigureLogging((hostingContext, loggingBuilder) => { var loggingConfiguration = hostingContext.Configuration.GetSection("Logging"); if (!string.IsNullOrWhiteSpace( loggingConfiguration["ApplicationInsights:InstrumentationKey"])) { var logLevel = loggingConfiguration["LogLevel:Default"]; loggingBuilder.AddApplicationInsights(loggingConfiguration ["ApplicationInsights:InstrumentationKey"]?.ToString() ?? ""); loggingBuilder.AddFilter<ApplicationInsightsLoggerProvider> ("", Enum.Parse<LogLevel>(logLevel ?? "Information")); loggingBuilder.AddFilter<ApplicationInsightsLoggerProvider> ("Default", Enum.Parse<LogLevel>(logLevel ?? "Warning")); } }); return webHostBuilder; } } Configure logging to Application Insights in the Startup class Write the following code in the ConfigureServices method to add ApplicationInsightsTelemetry to the request processing pipeline. var instrumentationKey = Configuration.GetValue<string> ("ApplicationInsights:InstrumentationKey"); services.AddApplicationInsightsTelemetry(instrumentationKey); Create logs in the controller method in .NET Core The following code listing shows how you can log data from the controller. public class ValuesController : ControllerBase { private readonly ILogger _logger; public ValuesController(ILogger<ValuesController> logger) { _logger = logger; } [HttpGet] public ActionResult<string> Get() { _logger.LogInformation("This is a test for checking the logger" + DateTime.Now.ToLongTimeString()); return "Hello World"; } } Application Insights can monitor request rates, response times, exceptions, failure rates, and even custom metrics you write in your application’s code. Further, Application Insights supports applications in a variety of languages on several platforms, and it works with several logging frameworks. In a future post here, we’ll examine how we can use a sink for Serilog that is capable of writing log data to Application Insights. Related content analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft rebrands Azure AI Studio to Azure AI Foundry The toolkit for building generative AI applications has been packaged with new updates to form the Azure AI Foundry service. By Anirban Ghoshal Nov 19, 2024 4 mins Microsoft Azure Generative AI Development Tools analysis Understanding Hyperlight, Microsoft’s minimal VM manager Microsoft is making its Rust-based, functions-focused VM tool available on Azure at last, ready to help event-driven applications at scale. By Simon Bisson Nov 14, 2024 8 mins Microsoft Azure Rust Serverless Computing analysis GitHub Copilot learns new tricks GitHub and Microsoft have taken their AI-powered programming assistant into new territories, tackling code reviews, simple web apps, Java upgrades, and Azure help and troubleshooting. By Simon Bisson Nov 07, 2024 8 mins GitHub Java Microsoft Azure Resources Videos