简体   繁体   中英

Serilog Sink Not Logging From Lambda

For my WebAPI, .UseSerilog() seems to work as expected on the LocalEntryPoint om my.Net Core 3.1 api running on my local box. However, when i deploy to AWS Lambda using LambdaEntryPoint's IWebHostBuilder it does not seem to log anything. My LambdaEntryPoint's IWebhostBuilder is:

 protected override void Init(IWebHostBuilder builder)
    {
        try
        {
            builder
               .ConfigureLogging(logger =>
                {
                  logger.ClearProviders();
                  logger.AddSerilog(dispose: true);
                );
                
              
            Log.Information("The IWebHostBuilder has been built");

        }
        catch (System.Exception ex)
        {
            Log.Fatal(ex, ex.Message);
        }
        finally
        {
            Log.CloseAndFlush();
        }

       
    }

Has anyone found a way to log using serilog in applications deployed in AWS Lambda?

You're going to want to use the.UseSerilog() extension menthod of the IWebHostBuilder directly like so:

protected override void Init(IWebHostBuilder builder)
{
     builder
         .UseSerilog()
         .UseStartup<Startup>();
}

My understanding is that this overrides the default ILogger implementation of Microsoft.Extensions.Logging namespace.

Then in your Startup class's ConfigureServices(IServiceCollection services) method you would implement a singleton of the Serilog.Core.Logger like so:

var loggerConfig = new LoggerConfiguration()
                .ReadFrom.Configuration(Configuration)
                .Enrich.WithThreadId()
                .Enrich.FromLogContext()
                .Enrich.WithProperty("Application", "MyApplicationName")
                .Enrich.WithProperty("Machine", Environment.MachineName)
                .WriteTo.Console(new RenderedCompactJsonFormatter());

var logger = loggerConfig.CreateLogger();
            services.AddSingleton<Logger>(logger);

At this point you've dependency injected the logger into your aspnetcore app and can use it in a controller like so:

private readonly Logger _log;

public DefaultController(Logger logger)
{
     _log = logger;
}

[HttpGet]
public IActionResult Get()
{
     _log.Information("This is an example of an information log");
     return Ok(new string[] { "value1", "value2" });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM