2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
8 -- luacheck: ignore 213/level
11 local ipairs
= ipairs
;
12 local require
= require
;
17 local level_sinks
= {};
21 local function init(name
)
22 local log_debug
= make_logger(name
, "debug");
23 local log_info
= make_logger(name
, "info");
24 local log_warn
= make_logger(name
, "warn");
25 local log_error
= make_logger(name
, "error");
27 return function (level
, message
, ...)
28 if level
== "debug" then
29 return log_debug(message
, ...);
30 elseif level
== "info" then
31 return log_info(message
, ...);
32 elseif level
== "warn" then
33 return log_warn(message
, ...);
34 elseif level
== "error" then
35 return log_error(message
, ...);
40 function make_logger(source_name
, level
)
41 local level_handlers
= level_sinks
[level
];
42 if not level_handlers
then
44 level_sinks
[level
] = level_handlers
;
47 local logger
= function (message
, ...)
48 for i
= 1,#level_handlers
do
49 level_handlers
[i
](source_name
, level
, message
, ...);
56 local function reset()
57 for level
, handler_list
in pairs(level_sinks
) do
58 -- Clear all handlers for this level
59 for i
= 1, #handler_list
do
60 handler_list
[i
] = nil;
65 local function add_level_sink(level
, sink_function
)
66 if not level_sinks
[level
] then
67 level_sinks
[level
] = { sink_function
};
69 level_sinks
[level
][#level_sinks
[level
] + 1 ] = sink_function
;
73 local function add_simple_sink(simple_sink_function
, levels
)
74 local format = require
"util.format".format;
75 local function sink_function(name
, level
, msg
, ...)
76 return simple_sink_function(name
, level
, format(msg
, ...));
78 for _
, level
in ipairs(levels
or {"debug", "info", "warn", "error"}) do
79 add_level_sink(level
, sink_function
);
85 make_logger
= make_logger
;
87 add_level_sink
= add_level_sink
;
88 add_simple_sink
= add_simple_sink
;