From 936a1afbc2b4e4f6fefed945fb1449197ba48c13 Mon Sep 17 00:00:00 2001 From: Manfred Touron <94029+moul@users.noreply.github.com> Date: Wed, 12 Jan 2022 09:15:26 +0000 Subject: [PATCH] feat: add CheckLevel helper Signed-off-by: Manfred Touron <94029+moul@users.noreply.github.com> --- README.md | 3 +++ zapfilter.go | 5 +++++ zapfilter_test.go | 31 +++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/README.md b/README.md index de2ec7f..5ee2d7f 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,9 @@ func CheckAnyLevel(logger *zap.Logger) bool CheckAnyLevel determines whether at least one log level isn't filtered-out by the logger. +func CheckLevel(logger *zap.Logger, level zapcore.Level) bool + CheckLevel determines whether a specific log level would produce log or not. + func NewFilteringCore(next zapcore.Core, filter FilterFunc) zapcore.Core NewFilteringCore returns a core middleware that uses the given filter function to determine whether to actually call Write on the next core in the diff --git a/zapfilter.go b/zapfilter.go index f948c1a..087e0e0 100644 --- a/zapfilter.go +++ b/zapfilter.go @@ -35,6 +35,11 @@ func CheckAnyLevel(logger *zap.Logger) bool { return false } +// CheckLevel determines whether a specific log level would produce log or not. +func CheckLevel(logger *zap.Logger, level zapcore.Level) bool { + return logger.Check(level, "") != nil +} + type filteringCore struct { next zapcore.Core filter FilterFunc diff --git a/zapfilter_test.go b/zapfilter_test.go index 3f25c6b..3a2fb71 100644 --- a/zapfilter_test.go +++ b/zapfilter_test.go @@ -436,6 +436,37 @@ func ExampleCheckAnyLevel() { // true } +func ExampleCheckLevel() { + c := zap.NewExample().Core() + logger := zap.New(zapfilter.NewFilteringCore(c, zapfilter.MustParseRules("debug:*.* info:demo*"))) + + fmt.Println(zapfilter.CheckLevel(logger, zap.DebugLevel)) + fmt.Println(zapfilter.CheckLevel(logger.Named("demo"), zap.DebugLevel)) + fmt.Println(zapfilter.CheckLevel(logger.Named("blahdemo"), zap.DebugLevel)) + fmt.Println(zapfilter.CheckLevel(logger.Named("demoblah"), zap.DebugLevel)) + fmt.Println(zapfilter.CheckLevel(logger.Named("blah"), zap.DebugLevel)) + fmt.Println(zapfilter.CheckLevel(logger.Named("blah.blah"), zap.DebugLevel)) + fmt.Println(zapfilter.CheckLevel(logger, zap.InfoLevel)) + fmt.Println(zapfilter.CheckLevel(logger.Named("demo"), zap.InfoLevel)) + fmt.Println(zapfilter.CheckLevel(logger.Named("blahdemo"), zap.InfoLevel)) + fmt.Println(zapfilter.CheckLevel(logger.Named("demoblah"), zap.InfoLevel)) + fmt.Println(zapfilter.CheckLevel(logger.Named("blah"), zap.InfoLevel)) + fmt.Println(zapfilter.CheckLevel(logger.Named("blah.blah"), zap.InfoLevel)) + // Output: + // false + // false + // false + // false + // false + // true + // false + // true + // false + // true + // false + // false +} + func Example_with() { core := zap.NewExample().Core() logger := zap.New(zapfilter.NewFilteringCore(core, zapfilter.ByNamespaces("demo1.*,demo3.*")))