serilog / serilog-settings-configuration

A Serilog configuration provider that reads from Microsoft.Extensions.Configuration
Apache License 2.0
446 stars 129 forks source link

Logs are not being written in Azure Application Insights #373

Closed viveknuna closed 1 year ago

viveknuna commented 1 year ago

I am using 3.4.0 version of Serilog.Settings.Configuration.

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);
        }
    }

Below line is added in Startup.cs ConfigureServices method.

services.AddApplicationInsightsTelemetry();

My application has the below configuration.

image

viveknuna commented 1 year ago

I have added the APPLICATIONINSIGHTS_CONNECTION_STRING variable as well in my app service in azure. it's still not logging.

sungam3r commented 1 year ago

Try append SelfLog.Enable(Console.Error) at the very beginning of the program to debug issues with configuration.

bartelink commented 1 year ago

As per the responses on https://github.com/serilog/serilog/issues/1892, I would recommend re-asking this on stackoverflow - it's a good place to work through config issues like this (and you have most of the relevant inputs for such a question right here). Only very few random people follow sink repos on github (I don't follow this one, but got here looking for cross-posting).

nblumhardt commented 1 year ago

This repository is not related to the Application Insights sink.