From ba8df8cb331558f12329ce75396c6646fdb6b73b Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Wed, 25 Dec 2019 18:53:37 +0000 Subject: [PATCH] src/ln: support filters --- spec/ln_spec.lua | 29 ++++++++++++++++++++++++++--- src/ln.lua | 20 ++++++++++++++------ 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/spec/ln_spec.lua b/spec/ln_spec.lua index c326fa2..eb1527c 100644 --- a/spec/ln_spec.lua +++ b/spec/ln_spec.lua @@ -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) @@ -59,14 +72,24 @@ describe("ln", function() assert.truthy(string.find(msg, 'foo="bar with spaces"')) end) 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) diff --git a/src/ln.lua b/src/ln.lua index be5b336..70933dc 100644 --- a/src/ln.lua +++ b/src/ln.lua @@ -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