serilog-contrib / serilog-sinks-applicationinsights

A Serilog sink that writes events to Microsoft Azure Application Insights
Apache License 2.0
220 stars 72 forks source link

Updated Azure Function section in README.md #191

Closed zyofeng closed 2 years ago

zyofeng commented 2 years ago

This is the recommended approach by Microsoft https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection#registering-services

Logging services If you need your own logging provider, register a custom type as an instance of ILoggerProvider, which is available through the Microsoft.Extensions.Logging.Abstractions NuGet package.

Application Insights is added by Azure Functions automatically.

nblumhardt commented 2 years ago

Thanks for this @zyofeng!

The returned value from CreateLogger() is a logger, not a logger configuration; assigning it to Log.Logger but also passing it through the SerilogLoggerProvider should give us the best of both worlds (fully-configured Serilog, and using the telemetry client provided by Azure Functions):

[assembly: FunctionsStartup(typeof(MyFunctions.Startup))]
namespace MyFunctions
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddSingleton<ILoggerProvider>((sp) => 
            {
                Log.Logger = new LoggerConfiguration()
                    .Enrich.FromLogContext()
                    .WriteTo.ApplicationInsights(sp.GetRequiredService<TelemetryClient>(), TelemetryConverter.Traces)
                    .CreateLogger();
                return new SerilogLoggerProvider(Log.Logger, true);
            });
        }
    }
}

Look good to you?

nblumhardt commented 2 years ago

Thanks for the updates. To make it easier to review and merge PRs it helps to keep each PR to a single logical change. I think the instrumentation key support is worth exploring via another PR - can this one stick to the README updates though? Thanks!

zyofeng commented 2 years ago

okay let me start again, will abandon this PR