Add Application Insights to a Web Site using the Open Telemetry Client

October 14, 2023

I’ve recently been playing with the Open Telemetry Client for .Net. In this post, I cover the basics of getting it running inside a .Net Web App and exporting it to App Insights.

For reference, this code if from my NoSearch site. If you’re interested, the links at the bottom of this post are also here inside that app.

The first step is to import the relevant libraries:

Install-Package Azure.Monitor.OpenTelemetry.Exporter 
Install-Package OpenTelemetry.Exporter.Console
Install-Package OpenTelemetry.Extensions.Hosting

These should allow for basic logging. The next step is, in Program.cs (or `Startup.cs“ if you’re on an earlier .Net version), add the following line:

builder.Services.AddLogging(builder => builder.AddOpenTelemetry(options =>
{
    options.AddConsoleExporter();
    options.AddAzureMonitorLogExporter();
}));

You’ll also need the following using statements for that:

using OpenTelemetry;
using OpenTelemetry.Logs;

What this will give you is an ILoggerProvider - we’ll come back to that shortly. First, let’s create a logger extension class; here’s mine:

public class LogEvents
{
    public const int SEARCH = 1000;
}

public static partial class ApplicationLogs
{
    [LoggerMessage(EventId = LogEvents.SEARCH, 
      Level = LogLevel.Information, 
      Message = "Search Results called {searchText}")]
    public static partial void SearchCalled(
        this ILogger logger, string searchText);
    
}

This allows you to call a log method in a more structured way; for example:

_logger.SearchCalled(searchText);

Now let’s come back to the loggerProvider that we mentioned earlier:

public SearchService(ILoggerProvider loggerProvider)
{    
    _logger = loggerProvider.CreateLogger(nameof(SearchService));            
}

To run this, you can use the environmental variable APPLICATIONINSIGHTS_CONNECTION_STRING. Locally, you can configure this in the launchSettings.json:

  "profiles": {
    "NoSearch.App": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "localhost:5062",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "APPLICATIONINSIGHTS_CONNECTION_STRING=
          "InstrumentationKey=keyhere;
          IngestionEndpoint=endpointhere"
      }
    },

References

https://learn.microsoft.com/en-us/azure/azure-monitor/app/opentelemetry-enable?tabs=net

https://github.com/open-telemetry/opentelemetry-dotnet/tree/main#getting-started

https://andrewlock.net/defining-custom-logging-messages-with-loggermessage-define-in-asp-net-core/

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024