diff options
Diffstat (limited to 'util/logger.lua')
-rw-r--r-- | util/logger.lua | 83 |
1 files changed, 67 insertions, 16 deletions
diff --git a/util/logger.lua b/util/logger.lua index 8d983605..26206d4d 100644 --- a/util/logger.lua +++ b/util/logger.lua @@ -1,23 +1,74 @@ +-- Prosody IM +-- Copyright (C) 2008-2010 Matthew Wild +-- Copyright (C) 2008-2010 Waqas Hussain +-- +-- This project is MIT/X11 licensed. Please see the +-- COPYING file in the source package for more information. +-- + +local pcall = pcall; + +local find = string.find; +local ipairs, pairs, setmetatable = ipairs, pairs, setmetatable; -local format = string.format; -local print = print; -local debug = debug; -local tostring = tostring; module "logger" +local level_sinks = {}; + +local make_logger; + function init(name) - --name = nil; -- While this line is not commented, will automatically fill in file/line number info - return function (level, message, ...) - if not name then - local inf = debug.getinfo(3, 'Snl'); - level = level .. ","..tostring(inf.short_src):match("[^/]*$")..":"..inf.currentline; - end - if ... then - print(level, format(message, ...)); - else - print(level, message); - end + local log_debug = make_logger(name, "debug"); + local log_info = make_logger(name, "info"); + local log_warn = make_logger(name, "warn"); + local log_error = make_logger(name, "error"); + + return function (level, message, ...) + if level == "debug" then + return log_debug(message, ...); + elseif level == "info" then + return log_info(message, ...); + elseif level == "warn" then + return log_warn(message, ...); + elseif level == "error" then + return log_error(message, ...); end + end +end + +function make_logger(source_name, level) + local level_handlers = level_sinks[level]; + if not level_handlers then + level_handlers = {}; + level_sinks[level] = level_handlers; + end + + local logger = function (message, ...) + for i = 1,#level_handlers do + level_handlers[i](source_name, level, message, ...); + end + end + + return logger; +end + +function reset() + for level, handler_list in pairs(level_sinks) do + -- Clear all handlers for this level + for i = 1, #handler_list do + handler_list[i] = nil; + end + end end -return _M;
\ No newline at end of file +function add_level_sink(level, sink_function) + if not level_sinks[level] then + level_sinks[level] = { sink_function }; + else + level_sinks[level][#level_sinks[level] + 1 ] = sink_function; + end +end + +_M.new = make_logger; + +return _M; |