避免在带有 Serilog 的 AWS Lambda 上使用 netcore2.0 记录两次

Avoid logging twice using netcore2.0 on AWS Lambda with Serilog

将我的 netcore 项目升级到 2.0 后,当我的应用程序在使用 Serilog 框架的 AWS Lambda 上 运行 时,我看到了双重日志。请在下面查看我的设置:

    public void ConfigureServices(IServiceCollection services)
    {
        ...

        // Setup logging
        Serilog.Debugging.SelfLog.Enable(Console.Error);
        var logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .Enrich.FromLogContext();

        if (GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "").Equals("local"))
            logger.WriteTo.Console();
        else
            logger.WriteTo.Console(new JsonFormatter());

        Log.Logger = logger.CreateLogger();

        ...
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddSerilog();
        ...
    }

关于为什么会突然出现这种情况有什么想法吗? Lambda 抓取任何控制台日志语句并插入到 cloudwatch 中,但现在是两次并以两种不同的格式插入。例如

[Information] PodioDataCollector.Controllers.CustomerController: Validating API Key

{ "Timestamp": "2018-02-14T08:12:54.7921006+00:00", "Level": "Information", "MessageTemplate": "Validating API Key", "Properties": { "SourceContext": "...", "ActionId": "...", "ActionName": "...", "RequestId": "...", "RequestPath": "...", "CorrelationId": "..." } }

我只期望格式为 json 的日志消息。这开始于我升级到 netcore2.0

提前致谢

日志实现和 Serilog 提供程序在 Core 2.0 中都发生了一些变化。

您将需要:https://github.com/serilog/serilog-aspnetcore 而不是 Serilog.Extensions.Logging(设置说明在 README 中)。

如果您使用 Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction 作为 lambda 入口点的基础 class,它会在调用 Init 方法的覆盖之前在日志记录提供程序中包含一个默认记录器。我相信您可以使用如下所示的 Init 方法来避免双重记录。

public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
{
    public LambdaEntryPoint()
    {
        var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", true)
            .AddEnvironmentVariables()
            .Build();

        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(configuration)
            .WriteTo.Console(new JsonFormatter())
            .CreateLogger();
    }

    protected override void Init(IWebHostBuilder builder)
    {
        builder.ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.ClearProviders();
                loggingBuilder.AddSerilog();
            })
            .UseStartup<Startup>();
    }
}