【发布时间】:2020-04-23 23:46:14
【问题描述】:
我有一个在 AWS Lambda 中运行的 .NET Core 2 WebAPI 应用程序。我正在使用 Serilog AwsCloudWatch 接收器。我还实现了来自 Datalust SerilogMiddleware example 的中间件。
这一切都可以在我的开发环境中完美运行(日志被写入正确的 CloudWatch 日志组)。但是,当应用程序在 Lambda 中运行时,不会发生日志记录。我启用了 Serilog SelfLog,但没有记录任何错误,所以我不认为这是 AWS 凭证问题。
这是我的日志配置:
private Serilog.Core.Logger ConfigureLogger(IHostingEnvironment env)
{
Serilog.Debugging.SelfLog.Enable(Console.Error);
// Base configuration
var logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithThreadId();
// Configure Sink: AWS CloudWatch
var cloudWatchLogsClient = new AmazonCloudWatchLogsClient("ACCESS_KEY_ID", "SECRET_ACCESS_KEY", RegionEndpoint.GetBySystemName(awsConfig.CloudWatchRegion));
var logLevel = env.IsProduction() ? LogEventLevel.Information : LogEventLevel.Debug;
logger.WriteTo.AmazonCloudWatch(new CloudWatchLogSinkOptions(env, logLevel), cloudWatchLogsClient);
// Configure Sink: Console (only for Debug environment)
if (env.IsDebug())
{
logger.WriteTo.Console(LogEventLevel.Debug);
}
return logger.CreateLogger();
}
这是 CloudWatchSinkOptions 的实现:
public class CloudWatchLogSinkOptions : ICloudWatchSinkOptions
{
public CloudWatchLogSinkOptions(IHostingEnvironment env, LogEventLevel level = LogEventLevel.Information)
{
LogGroupName += env.EnvironmentName;
MinimumLogEventLevel = level;
}
#region Settings
public LogEventLevel MinimumLogEventLevel { get; set; }
public int BatchSizeLimit { get; set; } = 100;
public TimeSpan Period { get; set; } = TimeSpan.FromSeconds(10);
public LogGroupRetentionPolicy LogGroupRetentionPolicy { get; set; } = LogGroupRetentionPolicy.OneYear;
public bool CreateLogGroup { get; set; } = true;
public string LogGroupName { get; set; } = "WebApi-ApplicationLog/";
public ILogStreamNameProvider LogStreamNameProvider { get; set; } = new DefaultLogStreamProvider();
public ITextFormatter TextFormatter { get; set; }= new SerilogTextFormatter();
public byte RetryAttempts { get; set; } = 5;
public int QueueSizeLimit { get; set; }
#endregion
#region Defaults
public const LogEventLevel DefaultMinimumLogEventLevel = LogEventLevel.Information;
public const int DefaultBatchSizeLimit = 100;
public const bool DefaultCreateLogGroup = true;
public const byte DefaultRetryAttempts = 5;
public static readonly TimeSpan DefaultPeriod = TimeSpan.FromSeconds(10);
#endregion
}
我相信我已经包含了所有必需的 Serilog 包:
最后,我为 Lambda 提供了对 CloudWatch Logs 的适当访问权限:
我不知道从这里去哪里。正如我之前所说,这在开发(调试)环境中效果很好。它在 Lambda 中不起作用,SelfLog 不会产生错误输出。
有人有解决这个问题的建议吗?感谢您的帮助!
【问题讨论】:
标签: aws-lambda serilog