File

mod_log_json/mod_log_json.lua @ 3732:21cfbdaac767

mod_log_json: JSON log sink
author Kim Alvefur <zash@zash.se>
date Thu, 18 Oct 2018 15:41:52 +0200
child 3733:9a3d25311fd9
line wrap: on
line source

local pack = require "util.table".pack;
local json = require "util.json";
local array = require "util.array";
local datetime = require "util.datetime".datetime;

module:set_global();

local function sink_maker(config)
	local logfile = io.open("blah.json", "a");
	logfile:setvbuf("no");
	return function (source, level, message, ...)
		local args = pack(...);
		for i = 1, args.n do
			if args[i] == nil then
				args[i] = json.null;
			elseif type(args[i]) ~= "string" or type(args[i]) ~= "number" then
				args[i] = tostring(args[i]);
			end
		end
		args.n = nil;
		local payload = {
			datetime = datetime(),
			source = source,
			level = level,
			message = message,
			args = array(args);
		};
		logfile:write(json.encode(payload), "\n");
	end
end

require"core.loggingmanager".register_sink_type("json", sink_maker);