示例工程 27-debugging-and-observability

27-debugging-and-observability/03-structured-log/main.lua

lua · 0.8 KB

-- @runtimes lua54 luajit
--- 演示:结构化日志一行 JSON。
local M = {}
 
local function escape(text)
	return text:gsub("\\", "\\\\"):gsub('"', '\\"'):gsub("\n", "\\n")
end
 
local function log_line(level, message, fields)
	local parts = {
		('"level":"%s"'):format(escape(level)),
		('"message":"%s"'):format(escape(message)),
	}
	for key, value in pairs(fields or {}) do
		parts[#parts + 1] = ('"%s":"%s"'):format(escape(key), escape(tostring(value)))
	end
	return "{" .. table.concat(parts, ",") .. "}"
end
 
--- @return table { line = string, has_request_id = boolean }
function M.run(log)
	log = log or print
	local line = log_line("info", "started", { request_id = "r-1" })
	log(line)
	return { line = line, has_request_id = line:find("request_id", 1, true) ~= nil }
end
if not ... then
	M.run()
end
return M