AWS Lambda和ASP.NET Core日志记录

时间:2020-08-07 12:46:16

标签: c# .net-core aws-lambda amazon-cloudwatch

我有一个使用以下设置在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日志中的最终结果如下所示: enter image description here

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

我只是使用Microsoft的ASP.NET Core默认记录器界面ILogger<MySampleController>,然后调用

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

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

谢谢!

0 个答案:

没有答案