Avoid logging twice using netcore2.0 on AWS Lambda

2019-07-20 20:44发布

问题:

After upgrading my netcore project to 2.0, i see double logs when my application is running on AWS Lambda, which utilizes the Serilog framework. Please see my setup below:

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

        ...
    }

and

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

Any ideas as to why this suddenly might be the case? Lambda grabs any console log statements and inserts into cloudwatch, but now twice and in two different formats. Eg.

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

and

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

I only expected the log message formatted in json. This started when i upgraded to netcore2.0

Thanks in advance

回答1:

The logging implementation, and Serilog provider, have both changed a little in Core 2.0.

You will need: https://github.com/serilog/serilog-aspnetcore instead of Serilog.Extensions.Logging (setup instructions are on the README).



回答2:

If you are using Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction as the base class for your lambda entrypoint, it includes a default logger in the logging providers before calling your override of the Init method. I believe you could use an Init method such as the following to avoid the dual-logging.

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