Search code examples
azure.net-coreazure-application-insightsserilogilogger

Azure Function Logging with Serilog to Application Insights


We use Azure Function V3 with dot net core 3.1 and log traces and events to Application Insights. This works quite fine. But we want to add object data to the log payload and therefore we use Serilog.

If we use the ILogger interface from namespace Microsoft.Extensions.Logging the object won't be serialized correct.

_logger.LogInformation("Test {@model}", testmodel);

If we use the Serilog interface it works and the data will be serialized in Application Insights:

logger.Information("Test Serilog {@model}", testmodel);

Serilog

The Startup.cs looks like that:

public class Startup : FunctionsStartup
{
  public override void Configure(IFunctionsHostBuilder builder)
  {
    var logger = new LoggerConfiguration()
      .WriteTo.ApplicationInsights(TelemetryConfiguration.CreateDefault(), TelemetryConverter.Traces, Serilog.Events.LogEventLevel.Information)
      .Destructure.ToMaximumCollectionCount(10)
      .Destructure.ToMaximumDepth(4)
      .CreateLogger();
    builder.Services.AddLogging(c => c.AddSerilog(logger));
    // Add other services
  }
}

Solution

  • Are you set on using Serilog? Otherwise the easier (and officially documented) approach might be to use an AppInsights TelemetryClient inside your Function. This way you can track all kinds of events and telemetry to AppInsights:

    https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library?tabs=v2%2Ccmd#log-custom-telemetry-in-c-functions