When you are using the Microsoft ILogger
abstraction in your C#/dotnet code and have an AWS Lambda composition root, it's useful to use the "Amazon.Lambda.Logging.AspNetCore" package to wire up the Lambda logging implementation.
Start by adding a reference to the "Amazon.Lambda.Logging.AspNetCore" NuGet package and then add the below setup to your DI container bootstrapping code:
context.Services.AddLogging(builder =>
{
builder.AddLambdaLogger(new LambdaLoggerOptions(configuration));
if (!Enum.TryParse<LogLevel>(Environment.GetEnvironmentVariable("AWS_LAMBDA_HANDLER_LOG_LEVEL") ?? "Information", out var absoluteMinimumLevel))
{
absoluteMinimumLevel = LogLevel.Information;
}
builder.SetMinimumLevel(absoluteMinimumLevel);
});
You must pass in IConfiguration, which you have built using "ConfigurationBuilder", adding sources such as appsettings.json, with the below config section present:
{
"Lambda.Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Warning"
}
}
}
It's worth noting that while you can have granular control over the log levels by namespace (plus Default) in the config, there is still an "absolute minimum" enforced by both the LambdaLogger and Microsoft's logging framework which, when otherwise not configured, defaults to "Information". This means that "by default" you can't opt in to any logger below this level, regardless of the configuration.
In order to override the "absolute minimum" (to include lower levels of log output), you can set the "AWS_LAMBDA_HANDLER_LOG_LEVEL" environment variable. This is automatically consumed internally by the AWS LambdaLogger and in the above code is propagated to the Microsoft logging builder so that both start from the same minimum and then apply the namespace level filtering on top.