首页 > 解决方案 > AWS Lambda 和 ASP.NET Core 日志记录

问题描述

我有一个在 AWS Lambda 中运行的 ASP.NET Core 3.1,设置如下:


  <ItemGroup>
    <PackageReference Include="Amazon.Lambda.AspNetCoreServer" Version="5.1.1" />
    <PackageReference Include="Amazon.Lambda.Logging.AspNetCore" Version="3.0.1" />
    <PackageReference Include="AutoMapper" Version="10.0.0" />
    <PackageReference Include="AutoMapper.Collection" Version="7.0.0" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.0.1" />
    <PackageReference Include="AWS.Logger.AspNetCore" Version="2.2.0" />
    
    <PackageReference Include="AWSSDK.DynamoDBv2" Version="3.3.105.26" />
    <PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="3.3.101" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.4" />
    ...

LambdaEntryPoint.cs:

    public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
    {
        protected override void Init(IWebHostBuilder builder)
        {
            builder
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    var env = hostingContext.HostingEnvironment;

                    config
                        .SetBasePath(env.ContentRootPath)
                        .AddJsonFile("appsettings.json", optional: true)
                        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

                    config.AddEnvironmentVariables();
                })
                
                .ConfigureLogging(logging =>
                {
                    logging.AddAWSProvider();
        
                    // // When you need logging below set the minimum level. Otherwise the logging framework will default to Informational for external providers.
                    // logging.SetMinimumLevel(LogLevel.Debug);
                })

                .UseStartup<Startup>()
            ;
        }
    }

appSettings.json

{
  "Logging": {
    "IncludeLogLevel": true,
    "IncludeCategory": true,
    "IncludeNewline": true,
    "IncludeException": true,
    "IncludeEventId": false,
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information",
      "System": "Warning",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Warning"
    }
  },
  
  "AllowedHosts": "*"
}

AWS CloudWatch 日志中的最终结果如下所示: 在此处输入图像描述

有无效字符[40m[32minfo[39m[22m[49m: 和多余的行。这只是一个示例,但在堆栈跟踪异常的情况下,日志会变得很长并且难以阅读。

我只是使用微软的 ASP.NET Core 默认记录器接口ILogger<MySampleController>,然后调用

this.logger.LogInformation($"Mapping done, took {sw.ElapsedMilliseconds} ms.");

我做错了什么?如何为 AWS Cloudwatch 正确配置日志?

谢谢!

标签: c#.net-coreaws-lambdaamazon-cloudwatch

解决方案


实际上与我们如何禁用添加到 ASP.NET Core 日志的 ANSI/VT100 颜色代码的答案相同

在您appsettings.jsonConsoleLogger.DisableColors 属性设置为true

    {
      "Logging": {
        "Console": {
          "DisableColors": true
        }
      }
    }

推荐阅读