Skip to content

Instantly share code, notes, and snippets.

@bivas
Last active December 17, 2015 11:49
Show Gist options
  • Save bivas/5605477 to your computer and use it in GitHub Desktop.
Save bivas/5605477 to your computer and use it in GitHub Desktop.
Lua logger module (inspired by log4j)
--[[
Lua log module
@author Eliran Bivas
Usage:
local log = require "log"
log.debug("some debug")
log.info("some info")
log.warn("some warn")
log.error("some error")
]]
local enum = require "enum"
local utils = require "utils"
local levels = {'DEBUG', 'INFO', 'WARN', 'ERROR'}
local keys = utils.invertTable(levels) -- based on http://stackoverflow.com/q/9754285/422651
local log = {
level = enum(levels), -- based on http://lua-users.org/lists/lua-l/2007-06/msg00433.html
rootLevel = 'DEBUG',
}
local function enabled(level)
if keys[log.rootLevel] <= keys[level] then return true end
return false
end
local function internalPrint(level, s)
if enabled(level) then
print(s)
end
end
log.debug = function(s)
internalPrint('DEBUG', '[DEBUG] ' .. s)
end
log.info = function(s)
internalPrint('INFO', '[INFO] ' .. s)
end
log.warn = function(s)
internalPrint('WARN', '[WARN] ' .. s)
end
log.error = function(s)
internalPrint('ERROR', '[ERROR] ' .. s)
end
return log
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment