【发布时间】:2018-11-20 17:16:55
【问题描述】:
我有一个使用 .NET Core (2.1) 构建的 AWS 无服务器 API 应用程序。我已经使用 Serilog 日志记录进行了设置,该日志记录使用 AWS Cloudwatch 接收器作为其日志记录目标。该项目依赖于核心逻辑所在的共享类库。
我注意到并非我的所有日志消息都进入 Cloudwatch。我的 API 控制器中的消息确实会成功记录,但来自共享类库的消息仅在我在本地运行时才会记录,而不是在使用实时 API 时记录。
这是我在 Startup 中的日志记录设置。
var awsCredentials = new BasicAWSCredentials(config["AWS:AccessKey"], config["AWS:SecretKey"]);
if (env.IsProduction())
{
var options = new CloudWatchSinkOptions
{
LogGroupName = config["AWS:Cloudwatch:LogGroup"],
LogStreamNameProvider = new LogStreamNameProvider(),
TextFormatter = new Serilog.Formatting.Json.JsonFormatter()
};
var client = new AmazonCloudWatchLogsClient(awsCredentials, RegionEndpoint.EUWest2);
Log.Logger = new LoggerConfiguration()
.Enrich.WithExceptionDetails()
.WriteTo
.AmazonCloudWatch(options, client)
.CreateLogger();
}
services.AddSingleton(Log.Logger);
我也尝试过添加services.AddLogging(builder => builder.AddSerilog());,但这并没有帮助。
我是这样使用的:
public class TestService
{
private readonly ILogger logger;
public TestService(ILogger logger)
{
this.logger = logger;
}
public void TestMethod()
{
this.logger.Information("Test Message");
}
}
【问题讨论】:
-
你试过
services.AddLogging(configuration => configuration.AddSerilog()).AddSingleton(Log.Logger);吗? -
刚试过。没有运气:(
-
您如何将
ILogger传递给您的服务?默认的依赖注入容器不会像在控制器中那样自动映射依赖。您必须调用ServiceProvider.GetService来检索要手动传递的依赖项,除非您自己编写该映射。 -
嗯,我没有为此设置任何东西。我认为 ILogger 会像其他任何服务一样被注入?我不想每次我想使用记录器时都必须做
ServiceProvider.GetService。当然,这违背了依赖注入的观点。没有ServiceProvider.GetService,有没有办法做到这一点? -
另外,我没有收到任何异常说 DI 顺便说一句失败了。就是拒绝登录直播环境。
标签: c# amazon-web-services logging asp.net-core amazon-cloudwatch