![](/img/trans.png)
[英]How can I turn off log level & category output in .NET Core logging to AWS CloudWatch?
[英]How to show log message with substituted parameters in structured logging output from Serilog on AWS Cloudwatch
我正在使用 AWS Cloudwatch 進行應用程序日志記錄。 我最近了解到我可以使用結構化日志來使我的日志更易於搜索。 我做了一些研究,並決定使用 Serilog 作為我的日志記錄工具。
我遇到的一個困難是,雖然我在 Cloudwatch 中看到結構化日志消息,但它沒有顯示完全格式化的日志消息。
例如,當我將其發送到日志時:
_logger.LogError("Hello {person}, {question} are you {time}?", "Dave", "how", "today");
我在 Cloudwatch 日志輸出中看到此消息
你好{person},{question}你是{time}嗎?
但是我在任何地方都看不到字符串的完全替換版本,即
你好戴夫,你今天好嗎?
我遵循了在 AWS https://martinjt.me/2020/02/16/serilog-and-cloudwatch-with-inbuilt-credentials/ 中設置 Serilog 以進行結構化日志記錄的演練,並最終得到了此代碼。
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseSerilog(SetupAWSLogging);
});
public class LoggingSettings
{
public string LogGroup { get; set; }
}
public static void SetupAWSLogging(WebHostBuilderContext hostingContext, LoggerConfiguration loggerConfiguration)
{
var config = hostingContext.Configuration;
var settings = config.GetSection("Logging").Get<LoggingSettings>();
loggerConfiguration
.MinimumLevel.Information()
.Enrich.FromLogContext()
.WriteTo.Console();
if (!string.IsNullOrEmpty(settings.LogGroup))
{
var options = new CloudWatchSinkOptions
{
LogGroupName = settings.LogGroup,
CreateLogGroup = true,
MinimumLogEventLevel = LogEventLevel.Information,
TextFormatter = new JsonFormatter()
};
var awsOptions = config.GetAWSOptions();
var cloudwatchClient = awsOptions.CreateServiceClient<IAmazonCloudWatchLogs>();
loggerConfiguration
.WriteTo.AmazonCloudWatch(options, cloudwatchClient);
}
}
這是在 Cloudwatch 中找到的完整條目
{
"Timestamp": "2021-07-05T09:08:32.5118371-06:00",
"Level": "Error",
"MessageTemplate": "Hello {person}, {question} are you {time}?",
"Properties": {
"person": "Dave",
"question": "how",
"time": "today",
"SourceContext": "Testing",
"ActionId": "54758041-ee5f-4297-a7b3-adaa5e675901",
"ActionName": "Testing.Ping (TestController)",
"RequestId": "80000007-0005-ff00-b63f-84710c7967bb",
"RequestPath": "/Testing/Ping"
}
}
我們自己構建消息所需的所有信息都在那里,但日志的可讀性不如我能看到替換的字符串。 我有什么遺漏或做錯了嗎? 也許這只是 Cloudwatch 中的一個配置來顯示帶有替換的字符串? 如果在那里完成我想可以減少原木尺寸會更好。
感謝大家的幫助。
最簡單的修復是:
TextFormatter = new JsonFormatter(renderMessage: true)
注意true
以呈現消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.