azure-application-insightsserilogserilog-aspnetcore

Logs are not being written in Azure Application Insights


I am using 3.4.0 version of Serilog.Settings.Configuration and Serilog.Sinks.ApplicationInsights version: 4.0.0

below is my appsettings.json.

  "Serilog": {
    "Using": [
      "Serilog.Sinks.ApplicationInsights"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "restrictedToMinimumLevel": "Information"
        }
      },
      {
        "Name": "ApplicationInsights",
        "Args": {
          "restrictedToMinimumLevel": "Information",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ]
  }

This is my Program.cs.

public class Program
    {
        public static void Main(string[] args)
        {
            ConfigureLogger();

            try
            {
                Log.Information("MyApp: Application Starting Up");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "MyApp: The applicaion failed to start correctly.");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
                .UseSerilog()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
        }

        private static void ConfigureLogger()
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", false, true)
                .Build();

            var configureLogger = new Action<IConfiguration, bool>((configuration, update) =>
            {
                try
                {
                    Log.Logger = new LoggerConfiguration()
                        .ReadFrom.Configuration(configuration, "Serilog")
                        .CreateLogger();

                    if (update)
                    {
                        Log.Logger.Information("MyApp: Updated logger configuration.");
                    }
                }
                catch (Exception ex)
                {
                    Log.Logger.Error(ex, "MyApp: Failed to update logger configuration.");
                }
            });

            var updateLoggerTimer = new Timer((state) =>
            {
                configureLogger(configuration, true);
            }, null, Timeout.Infinite, Timeout.Infinite);

            ChangeToken.OnChange(() => configuration.GetReloadToken(), () =>
            {
                // Use timer to debounce onchange, it fires twice when configuration changes
                updateLoggerTimer.Change(TimeSpan.FromSeconds(1), Timeout.InfiniteTimeSpan);
            });

            configureLogger(configuration, false);
        }
    }

The below line is added in Startup.cs ConfigureServices method.

services.AddApplicationInsightsTelemetry();

My application has the below configuration.

enter image description here

No logs:

enter image description here


Solution

  • From your previous thread I came to know that you are using ASP.NetCore 6.0, so no need of Startup.cs file here. All the code can be configured within the Program.cs file.

    Thanks @Roman Marusyk for the comment.

    Yes, you need to add the Application Insights Connection string in your appsettings.json file.

    My appsettings.json file:

    { 
        "Logging": {
          "ApplicationInsights": {
            "LogLevel": {
              "Default": "Debug",
              "Microsoft": "Error"
            }
          },
          "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
          }
        },
    
        "AllowedHosts": "*",
        "ApplicationInsights": {
          "ConnectionString": "InstrumentationKey=**********;IngestionEndpoint=https://westus2-2.in.applicationinsights.azure.com/;LiveEndpoint=https://****.livediagnostics.monitor.azure.com/"
        },
    
        "WriteTo": [
          {
            "Name": "ApplicationInsights",
            "Args": {
              "restrictedToMinimumLevel": "Information",
              "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights",
              "InstrumentationKey": "****"
            }
          }
        ],
        "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
        "Properties": {
          "Application": "Application Insights using Serilog"
        }
      }
    

    Thanks @SimonCropp I have taken reference from the GitHub link.

    My Program.cs file:

    using Serilog;
    using Serilog.Sinks.ApplicationInsights.TelemetryConverters;
    using static System.Net.Mime.MediaTypeNames;
    using System;
    
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddControllersWithViews();
    
    var ConnStr = builder.Configuration.GetSection("ApplicationInsights").GetValue<string>("ConnectionString");
    
    var log = new LoggerConfiguration()
        .Enrich.FromLogContext()
     .WriteTo.ApplicationInsights(ConnStr, new TraceTelemetryConverter())
     .CreateLogger();
    
    
    builder.Logging.AddSerilog(log);
    var app = builder.Build();
    
    app.Logger.LogInformation("Log from App");
    try
    {
        app.Logger.LogDebug("Debug Message");   
        app.Logger.LogWarning("Warning Message");
    }
    catch (Exception ex)
    {
        Log.Fatal(ex, "MyApp: The applicaion failed to start correctly.");
    }
    finally
    {
        Log.CloseAndFlush();
    }
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    
    app.UseAuthorization();
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.Run();
    

    Traces:

    enter image description here