question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Serilog logs aren't sent / written into Azure ApplicationInsights for .NET Core API and Worker Service

See original GitHub issue

I have a C# ASP .NET Core Web API application and an Worker Service application, but the logs from API and from Worker Service doesn’t arrive in Azure Application Insights, can see them only in Console and are written to files.

Both scenario tested:

  • API deployed in Azure AppService + Worker Service deployed as Windows service in Azure in an Windows Server Virtual Machine
  • API and Worker Service ran in debug mode from local machine in Visual Studio

Versions:

  • .NET 5.0
  • Microsoft.ApplicationInsights.AspNetCore 2.18.0 (installed for the API)
  • Microsoft.ApplicationInsights.WorkerService 2.18.0 (installed for the Worker Service)
  • Serilog 2.10.0
  • Serilog.Sinks.ApplicationInsights 3.1.0 (or 2.6.4)

Tried without success even downgrading Serilog.Sinks.ApplicationInsights to version 2.6.4 as suggested in this issue.

Have both API and Worker service configured the same way: API - Program.cs

var options = CommandLineOptions.Configure(args);
await Host.CreateDefaultBuilder(args)
	.ConfigureAppConfiguration(AppConfigurationServices.Configure)
	.ConfigureLogging(LoggerServices.Configure)
	.ConfigureServices(HostServices.Configure)
	.UseSerilog()
	.RunHostAsync(options);

Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));

Worker Service - Program.cs

await Host.CreateDefaultBuilder(args)
	  .ConfigureWebHostDefaults(webBuilder =>
	  {
		  webBuilder
			  .ConfigureAppConfiguration(AppConfigurationServices.Configure)
			  .ConfigureLogging(LoggingServices.Configure)
			  .UseStartup<Startup>();
	  })
	  .UseSerilog()
	  .Build()
	  .RunAsync();

Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));

I’m already supplying the Azure App Insights InstrumentationKey in appSettings.json two locations:

...
"ApplicationInsights": {
    "InstrumentationKey": "xxx-xyz"
  },
...
"Serilog": {
    "Using": [
      "Serilog",
      "Serilog.Sinks.Console",
      "Serilog.Sinks.File",
      "Serilog.Sinks.ApplicationInsights"
    ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/Services-.log",
          "rollingInterval": "Day"
        }
      },
      {
        "Name": "ApplicationInsights",
        "Args": {
          "instrumentationKey": "xxx-xyz",
          "restrictedToMinimumLevel": "Information",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ],
    "Enrich": [ "FromLogContext" ]
  }
...

When specifying InstrumentationKey only in ApplicationInsights and not under Serilog writer as well, iKey wasn’t present and i got: Application Insights Telemetry (unconfigured) {"name":"AppTraces", "time": "123...", ....}

After specifying InstrumentationKey in both places (ApplicationInsights and under Serilog writer) you can see multiple records like bellow in the Debug Output window from Visual Studio. Even enabling Serilog self diagnostic doesn’t produce any different output than this one from Debug Output window:

Application Insights Telemetry: {"name":"AppRequests", "time": "123...", "iKey": "xxx-xyz", ....}
Application Insights Telemetry: {"name":"AppMetrics", "time": "123...", "iKey": "xxx-xyz", ....}
Application Insights Telemetry: {"name":"AppTraces", "time": "123...", "iKey": "xxx-xyz", ....}

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:5
  • Comments:8

github_iconTop GitHub Comments

4reactions
ansaryansucommented, May 10, 2022

In .Net Core WEB API 6.0, In order to get app insights logs when running locally, Set “APPINSIGHTS_INSTRUMENTATIONKEY” environment variable in the launch settings.

“profiles”: { “ProfileName”: { “launchBrowser”: true, “environmentVariables”: { “ASPNETCORE_ENVIRONMENT”: “Development”, “APPINSIGHTS_INSTRUMENTATIONKEY”: “your-instrumentation-key” } }

2reactions
wertzuicommented, Mar 9, 2022

This works for me (replace my-key with your Instrumentation Key) appsettings.json

{
  "ApplicationInsights": {
    "InstrumentationKey": "my-key"
  },
  "Serilog": {
    "Using": [
      "Serilog.Sinks.ApplicationInsights"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Async",
        "Args": {
          "configure": [
            {
              "Name": "Console"
            },
            {
              "Name": "File",
              "restrictedToMinimumLevel": "Information",
              "path": "logs/log.log",
              "rollingInterval": "Day",
              "rollOnFileSizeLimit": true
            }
          ]
        }
      },
      {
        "Name": "ApplicationInsights",
        "Args": {
          "InstrumentationKey": "my-key",
          "restrictedToMinimumLevel": "Information",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ],
    "Enrich": [ "FromLogContext" ]
  }
}

Program.cs

public static class Programm
{
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .WriteTo.File("logs/log.log", rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true)
                .CreateBootstrapLogger();
            try
            {
                Log.Information("Starting up");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception e)
            {
                Log.Fatal(e, "Application start-up failed");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        private static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog((context, services, configuration) =>
                    configuration
                        .ReadFrom.Configuration(context.Configuration)
                        .ReadFrom.Services(services)
                        .Enrich.FromLogContext())
                .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Serilog logs aren't sent / written into Azure ...
I have a C# ASP .NET Core Web API application and an Worker Service application, but the logs from API and from Worker...
Read more >
Serilog logs aren't sent / written into Azure ...
I have a C# ASP .NET Core Web API application and an Worker Service application, but the logs from API and from Worker...
Read more >
Application Insights logging with .NET - Azure Monitor
In this article, you learn how to capture logs with Application Insights in .NET apps by using the Microsoft.Extensions.Logging.
Read more >
NET Core Worker Services with Application Insights and Serilog
It took me quite some time to implement Application Insights and file logging (Serilog) in my worker service, so I thought I might...
Read more >
Logging with Serilog and Application Insights
NET Core provides a simple logging abstraction with most of required logging features used by an application. Everywhere in the application, when logging...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found