Search code examples
c#amazon-web-serviceslambdaserilog.net-core-2.0

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


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


Solution

  • 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).