我正在使用 aws-logging-dotnet 库将应用程序日志写入 AWS Cloudwatch。
记录器是通过 json 文件配置的:
{
"Serilog": {
"Using": [ "AWS.Logger.SeriLog", "Serilog.Exceptions" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Hangfire": "Warning",
"Microsoft.AspNetCore": "Warning",
"Serilog.AspNetCore": "Warning",
"System": "Warning"
}
},
"Enrich": [ "WithMachineName", "WithProcessId", "WithProcessName", "FromLogContext", "WithExceptionDetails" ],
"Properties": {
"Application": "My Application Name"
},
"Region": "My AWS Region",
"LogGroup": "My AWS LogGroup",
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
],
"WriteTo:Async": {
"Name": "Async",
"Args": {
"configure": [
{
"Name": "AWSSeriLog",
"Args": {
"textFormatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
}
}
]
}
}
}
}
应用程序开始登录 AWS CW 后,它会创建一个专用流,如下所示:
我有兴趣获取 LogStreamName 的运行时值。 该应用程序在许多节点上运行,因此每个实例都登录到自己的流中。
我可以看到 LogStreamName 名称是由记录器内部管理的。然而似乎没有办法获得这个值。
public PutLogEventsRequest _request = new PutLogEventsRequest();
public LogEventBatch(string logGroupName, string streamName, int timeIntervalBetweenPushes, int maxBatchSize)
{
_request.LogGroupName = logGroupName;
_request.LogStreamName = streamName;
TimeIntervalBetweenPushes = TimeSpan.FromSeconds(timeIntervalBetweenPushes);
MaxBatchSize = maxBatchSize;
Reset(null);
}
在我发明黑客解决方案之前,有谁知道是否有一种干净的方式来阅读它?
简短的回答是否定的。 日志流名称由 AWSLoggerCore 类内部管理。 也没有办法覆盖它。
但是有一个开放请求:https://github.com/aws/aws-logging-dotnet/issues/195
您可以考虑选择此替代库:serilog-sinks-awscloudwatch https://github.com/Cimpress-MCP/serilog-sinks-awscloudwatch
这使您可以通过实现自己的 LogStreamNameProvider 来设置您喜欢的日志流名称:
var options = new CloudWatchSinkOptions
{
// the name of the CloudWatch Log group for logging
LogGroupName = logGroupName,
// the main formatter of the log event
TextFormatter = formatter,
// other defaults defaults
MinimumLogEventLevel = LogEventLevel.Information,
BatchSizeLimit = 100,
QueueSizeLimit = 10000,
Period = TimeSpan.FromSeconds(10),
CreateLogGroup = true,
LogStreamNameProvider = new MyLogStreamProvider(),
RetryAttempts = 5
};
...
public class MyLogStreamProvider : ILogStreamNameProvider
{
private readonly string DATETIME_FORMAT = "yyyy-MM-dd-hh-mm-ss";
// Customise your log stream name
public string GetLogStreamName()
{
return $"{DateTime.UtcNow.ToString(DATETIME_FORMAT)}_{Dns.GetHostName()}_{Guid.NewGuid()}";
}
}