使用 Serilog 将 JSON 格式的数据写入 AWS Cloudwatch

问题描述 投票:0回答:0

我想将 API 请求数据记录到 serilog 以用于某些分析目的,但我无法获得正确的格式。我在 Dot net Core 5 中使用 Serilog,我的记录器配置如下

LoggerConfiguration config = new LoggerConfiguration()
                .WriteTo.AmazonCloudWatch(
                    // The name of the log group to log to
                    logGroup: "DotNetLogging",
                    // A string that our log stream names should be prefixed with. We are just specifying the
                    // start timestamp as the log stream prefix
                    logStreamPrefix: DateTime.UtcNow.ToString("yyyyMMddHHmmssfff"),
                    appendUniqueInstanceGuid: false,
                    textFormatter: new JsonFormatter(),
                    // The AWS CloudWatch client to use
                    cloudWatchClient: client)
                .ReadFrom.Configuration(configuration)
                .Enrich.FromLogContext()
                .Enrich.WithMachineName()
                .Enrich.WithProperty("Application", appName)
                .Enrich.WithProperty("UserName", Environment.UserName);

但是cloudwatch中的输出类似于这个

{
    "Timestamp": "2023-02-26T18:59:37.1636016-05:00",
    "Level": "Error",
    "MessageTemplate": "test json",
    "Properties": {
        "ApiRequestData": "{\"Name\":\"John Doe\",\"occupation\":\"gardener\"}",
        "ApiStatus": "True",
        "ApiURL": "test.com",
        "LineNumber": 19,
        "Function": "RunProcess",
        "SourceFile": "testlogger.cs",
        "MachineName": "testmachine",
        "Application": "test"
    }
}

使用以下代码登录

Sample Class :

public class Test
    {
        public string Name { get; set; } = "John Doe";
        public string occupation { get; set; } = "gardener";
    }

Log Statement:

Log.Error("test json", true, "test.com", JsonConvert.SerializeObject(new Test()));

有人能告诉我如何在 cloudwatch 中为 Apirequestdata 属性获取类似 json 的格式吗?我已经编写了自定义代码来推送我在 Logcontext 中需要的所有属性以及 api 数据属性的行,如下所示

LogContext.PushProperty("ApiRequestData", ApiRequestData);
json amazon-web-services .net-core amazon-cloudwatch serilog
© www.soinside.com 2019 - 2024. All rights reserved.