如何使用 Ballerina 中的日志模块记录不带转义字符的 JSON?

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

当我使用日志模块记录某些内容时,日志消息会打印转义字符而不是解释它。例如,考虑以下代码。

import ballerina/log;

public function main() {
    json jsonObject = {
        "name": "John Doe",
        "age": 30,
        "city": "New York"
    };
    log:printInfo("Hello this is your json object: " + jsonObject.toJsonString());
}

当我运行上面的代码时,它会记录以下内容。

time = 2023-11-09T15:15:10.935+05:30 level = INFO module = nilushan/test message = "Hello this is your json object: {\"name\":\"John Doe\", \"age\":30, \"city\":\"New York\"}"

如何让程序记录没有转义字符的行?

ballerina
1个回答
0
投票

由于 JSON 对象传递给

message
参数,因此它会转换为 JSON 字符串,因为
message
参数期望打印用户期望的字符串。由于用例是按原样打印 JSON(即将 JSON 作为键值对打印),因此 JSON 参数应作为
payload
参数提供,如下所示。

import ballerina/log;

public function main() {
    json jsonObject = {
        "name": "John Doe",
        "age": 30,
        "city": "New York"
    };
    log:printInfo("Hello this is your json object", payload = jsonObject);
}

上面的代码生成以下输出:

time=2024-01-08T11:53:30.462+05:30 level=INFO module="" message="Hello this is your json object" payload={"name":"John Doe","age":30,"city":"New York"}
© www.soinside.com 2019 - 2024. All rights reserved.