src/ln: support filters

This commit is contained in:
Cadey Ratio 2019-12-25 18:53:37 +00:00
parent 3664cbb504
commit ba8df8cb33
2 changed files with 40 additions and 9 deletions

View File

@ -8,6 +8,8 @@ describe("ln", function()
it("has default_logger", function()
assert.truthy(ln.default_logger)
assert.truthy(ln.default_logger.formatter)
assert.truthy(ln.default_logger.filters)
end)
it("has LogfmtFormatter", function()
@ -29,21 +31,32 @@ describe("ln", function()
describe("default logger operations", function()
local lgr = ln.default_logger
local msg
lgr.filters = {
function(message) msg = message end,
}
it("can log", function()
lgr:log {foo = "bar"}
assert.truthy(string.find(msg, 'foo=bar'))
end)
it("can error", function()
lgr:err("vibe check failed", {foo = "bar"})
lgr:err("vibe check failed", {foo = "baz"})
assert.truthy(string.find(msg, 'foo=baz'))
assert.truthy(string.find(msg, 'vibe check failed'))
end)
it("takes multiple tables", function()
lgr:log({foo = "bar"}, {baz = "boz"})
assert.truthy(string.find(msg, 'foo=bar'))
assert.truthy(string.find(msg, 'baz=boz'))
end)
it("lets you override the formatter", function()
lgr.formatter = ln.JSONFormatter:new()
lgr:log {foo = "bar"}
assert.truthy(string.find(msg, "{"))
end)
end)
@ -61,12 +74,22 @@ describe("ln", function()
end)
describe("logger options", function()
local msg
local filter_func = function(message) msg = message end
local lgr = ln.Logger:new {
formatter = ln.LogfmtFormatter:new()
formatter = ln.LogfmtFormatter:new(),
filters = {
filter_func,
}
}
it("sets the formatter to non-nil", function()
assert.truthy(lgr.formatter)
end)
it("respects filters", function()
lgr:log {foo = "bar"}
assert.truthy(string.find(msg, 'foo=bar'))
end)
end)
end)

View File

@ -63,17 +63,25 @@ function Logger:log(...)
end
end
message = self.formatter:format(result)
print(message)
local message = self.formatter:format(result)
for _, v in pairs(self.filters) do
v(message)
end
end
function Logger:new(o)
if o == nil then
o = {
formatter = LogfmtFormatter:new()
}
o = {}
end
if o.formatter == nil then
o.formatter = LogfmtFormatter:new()
end
if o.filters == nil then
o.filters = {print}
end
setmetatable(o, self)
self.__index = self
return o