如何使用Ballerina的log模块无转义字符记录JSON
Ballerina日志输出JSON时去除转义字符的解决方法
当使用Ballerina的log模块记录包含JSON的日志时,直接拼接JSON字符串会导致输出中出现转义字符。例如以下代码:
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 = org/test message = "Hello this is your json object: {\"name\":\"John Doe\", \"age\":30, \"city\":\"New York\"}"
方法1:使用结构化日志参数(推荐)
避免将JSON字符串拼接到日志消息中,而是把JSON对象作为附加参数传递给日志函数。日志系统会自动解析结构化数据,无需转义:
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); }
输出示例:
time = 2023-11-09T15:15:10.935+05:30 level = INFO module = org/test message = "Hello this is your json object" name = "John Doe" age = 30 city = "New York"
方法2:自定义日志布局(嵌入JSON到消息文本)
如果需要将JSON直接嵌入到日志消息文本中,可通过自定义日志布局取消消息字段的引号包裹,从而避免转义:
- 创建日志配置文件
log_config.toml:
[log] layout = """time = ${time:yyyy-MM-dd'T'HH:mm:ss.SSSZ} level = ${level} module = ${module} message = ${message}"""
- 在代码中加载配置并输出日志:
import ballerina/log; public function main() returns error? { check log:loadConfig("log_config.toml"); 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+0530 level = INFO module = org/test message = Hello this is your json object: {"name":"John Doe", "age":30, "city":"New York"}
内容的提问来源于stack exchange,提问作者Nipuna Fernando
相关产品推荐
相关产品推荐

