1

Byte217 - Logging - Application Insights

 2 months ago
source link: https://byte217.com/logging-application-insights/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Logging – Application Insights

After or during deployment of a web app to Azure, Application Insights can be enabled for that Web App. There are many ways to log data in Azure. when I wrote this code Application Insights was the prefered way of doing it. As I use the logging mainly during development, I haven’t looked into newer alternatives yet.

Application Insights is used to store Telemetry data and logging data. This is configured and enabled seperately.
Storing data in Application Insights can be costly when using a storage container. Therefore, I have added two extra switches to easily switch of logging and storing of telemetry data.

To use Application Insights we have to add the following NuGet package:
Microsoft.Extensions.Logging.ApplicationInsights

Configuration

In the appSettings.json we add:

"Logging": {
"LogLevel": {
"Default": "Error"
"ApplicationInsights": {
"EnablePerformanceCounterCollectionModule": false,
"EnableRequestTrackingTelemetryModule": false,
"EnableEventCounterCollectionModule": false,
"EnableDependencyTrackingTelemetryModule": false,
"EnableAppServicesHeartbeatTelemetryModule": false,
"EnableAzureInstanceMetadataTelemetryModule": false,
"EnableQuickPulseMetricStream": false,
"EnableAdaptiveSampling": true,
"EnableHeartbeat": false,
"AddAutoCollectedMetricExtractor": false,
"RequestCollectionOptions.TrackExceptions": false,
"EnableDiagnosticsTelemetryModule": false
"EnableApplicationInsightsLogging": false,
"EnableApplicationInsightsTelemetry": false
"Logging": {
  "LogLevel": {
    "Default": "Error"
  }
},
"ApplicationInsights": {
  "EnablePerformanceCounterCollectionModule": false,
  "EnableRequestTrackingTelemetryModule": false,
  "EnableEventCounterCollectionModule": false,
  "EnableDependencyTrackingTelemetryModule": false,
  "EnableAppServicesHeartbeatTelemetryModule": false,
  "EnableAzureInstanceMetadataTelemetryModule": false,
  "EnableQuickPulseMetricStream": false,
  "EnableAdaptiveSampling": true,
  "EnableHeartbeat": false,
  "AddAutoCollectedMetricExtractor": false,
  "RequestCollectionOptions.TrackExceptions": false,
  "EnableDiagnosticsTelemetryModule": false
},
"EnableApplicationInsightsLogging":  false,
"EnableApplicationInsightsTelemetry": false

The Application Insights section contains all the settings that can be enabled or disabled. I found it useful to have two additional settings to enable or disable the Logging and Telemetry completely.

Middleware

Depending on the .NET Core framework version we add some extra code to the Startup.cs or Program.cs.

namespace LoggingExample
public class Program
public static void Main(string[] args)
var builder = WebApplication.CreateBuilder(args);
IServiceCollection services = builder.Services;
ConfigurationManager configuration = builder.Configuration;
#if !DEBUG
bool enableApplicationInsightsTelemetry = false;
enableApplicationInsightsTelemetry = configuration.GetValue<bool>("EnableApplicationInsightsTelemetry");
if (enableApplicationInsightsTelemetry)
services.AddApplicationInsightsTelemetry(configuration);
#endif
services.AddLogging(builder =>
builder.ClearProviders();
#if DEBUG
builder.AddSeq(configuration.GetSection("Seq"));
#else
bool enableApplicationInsightsLogging = false;
enableApplicationInsightsLogging = configuration.GetValue<bool>("EnableApplicationInsightsLogging");
if (enableApplicationInsightsLogging)
string connectionString = configuration.GetValue<string>("APPLICATIONINSIGHTS_CONNECTION_STRING");
if (!string.IsNullOrWhiteSpace(connectionString))
builder.AddApplicationInsights
(configureTelemetryConfiguration) => { configureTelemetryConfiguration.ConnectionString = connectionString; },
(applicationInsightsLoggerOptions) => { }
#endif
// Add services to the container.
services.AddRazorComponents()
.AddInteractiveServerComponents();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseExceptionHandler("/Error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseWebOptimizer();
app.UseStaticFiles();
app.UseAntiforgery();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.Run();
namespace LoggingExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            IServiceCollection services = builder.Services;
            ConfigurationManager configuration = builder.Configuration;

#if !DEBUG
            bool enableApplicationInsightsTelemetry = false;
            enableApplicationInsightsTelemetry = configuration.GetValue<bool>("EnableApplicationInsightsTelemetry");
            if (enableApplicationInsightsTelemetry)
            {
                services.AddApplicationInsightsTelemetry(configuration);
            }
#endif

            services.AddLogging(builder =>
            {
                builder.ClearProviders();
#if DEBUG
                builder.AddSeq(configuration.GetSection("Seq"));
#else
                bool enableApplicationInsightsLogging = false;
                enableApplicationInsightsLogging = configuration.GetValue<bool>("EnableApplicationInsightsLogging");
                if (enableApplicationInsightsLogging)
                {
                    string connectionString = configuration.GetValue<string>("APPLICATIONINSIGHTS_CONNECTION_STRING");
                    if (!string.IsNullOrWhiteSpace(connectionString))
                    {
                        builder.AddApplicationInsights
                        (
                            (configureTelemetryConfiguration) => { configureTelemetryConfiguration.ConnectionString = connectionString; },
                            (applicationInsightsLoggerOptions) => { }
                        );
                    }
                }
#endif
            });

            // Add services to the container.
            services.AddRazorComponents()
                    .AddInteractiveServerComponents();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseWebOptimizer();
            app.UseStaticFiles();
            app.UseAntiforgery();

            app.MapRazorComponents<App>()
               .AddInteractiveServerRenderMode();

            app.Run();
        }
    }
}

As you can see, I have included preprocessor directives to ensure that I won’t log to the Azure portal while developing. Only a release build will log to Application Insights when the configuration allows it. I suggest to include the “EnableApplicationInsightsLogging” and “EnableApplicationInsightsTelemetry” settings in your application configuration in the Azure portal. This makes it easier to quickly switch logging on or off when needed.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK