AWS CloudWatch日志中Logger.BeginScope设置的属性未显示
问题原因与解决方案
在.NET Core 3.1的AWS Lambda环境中,默认日志配置不会自动将BeginScope中的属性嵌入CloudWatch日志条目,需要通过以下步骤调整配置:
1. 安装专用Lambda日志包
确保项目已安装Amazon.Lambda.Logging.AspNetCore NuGet包,它是AWS官方为Lambda优化的日志提供器,能更好地处理Scope属性:
Install-Package Amazon.Lambda.Logging.AspNetCore
2. 配置日志以包含Scope属性
根据你的Lambda项目结构,在日志配置中开启IncludeScopes并设置合适的输出模板:
方式一:使用Startup类配置
public class Startup { public void ConfigureServices(IServiceCollection services) { // 其他服务注册逻辑 } public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.AddLambdaLogger(options => { options.LogLevel = LogLevel.Information; options.IncludeScopes = true; // 自定义日志模板,将Scope属性嵌入输出 options.Formatter = new LambdaLoggerFormatter { Template = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] {Scope} {Message:lj}" }; }); // 其他中间件配置 } }
方式二:使用HostBuilder配置(控制台式Lambda项目)
public class Function { public static void Main() { var host = new HostBuilder() .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddLambdaLogger(options => { options.IncludeScopes = true; options.Formatter = new LambdaLoggerFormatter { Template = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Scope} {Message}" }; }); }) .Build(); LambdaBootstrapBuilder.Create<Function>(host.Services) .Build() .RunAsync().Wait(); } public async Task<string> FunctionHandler(string input, ILambdaContext context) { var logger = host.Services.GetRequiredService<ILogger<Function>>(); using (logger.BeginScope(new Dictionary<string, object> { ["AwsRequestId"] = context.AwsRequestId })) { logger.LogInformation("Entered lambda {LambdaName}", context.FunctionName); } return "Processed"; } }
3. 可选:使用结构化JSON日志(更利于CloudWatch查询)
如果希望日志以JSON格式输出,让CloudWatch直接识别AwsRequestId等属性,可以配置JSON控制台格式化器:
.ConfigureLogging(logging => { logging.AddConsole(options => { options.FormatterName = "json"; options.IncludeScopes = true; }).AddConsoleFormatter<JsonConsoleFormatter, JsonConsoleFormatterOptions>(options => { options.IncludeScopes = true; }); })
配置完成后,CloudWatch日志中会显示类似[AwsRequestId=xxx] Entered lambda MyFunction的条目,或者JSON格式中直接包含AwsRequestId字段。
内容的提问来源于stack exchange,提问作者Navin
相关产品推荐
相关产品推荐

