From b9977338fda7de59b29a523acb22acbad2f0e103 Mon Sep 17 00:00:00 2001 From: Ryan Uber Date: Mon, 13 Oct 2014 22:38:12 -0700 Subject: [PATCH] agent: Filter messages logged to syslog. Fixes #272 --- command/agent/command.go | 2 +- command/agent/syslog.go | 9 ++++++++- command/agent/syslog_test.go | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 command/agent/syslog_test.go diff --git a/command/agent/command.go b/command/agent/command.go index eb1872e3c5..b23e3bc96d 100644 --- a/command/agent/command.go +++ b/command/agent/command.go @@ -235,7 +235,7 @@ func (c *Command) setupLoggers(config *Config) (*GatedWriter, *logWriter, io.Wri c.Ui.Error(fmt.Sprintf("Syslog setup failed: %v", err)) return nil, nil, nil } - syslog = &SyslogWrapper{l} + syslog = &SyslogWrapper{l, c.logFilter} } // Create a log writer, and wrap a logOutput around it diff --git a/command/agent/syslog.go b/command/agent/syslog.go index 9f08385d8f..b7aed636db 100644 --- a/command/agent/syslog.go +++ b/command/agent/syslog.go @@ -3,6 +3,7 @@ package agent import ( "bytes" "github.com/hashicorp/go-syslog" + "github.com/hashicorp/logutils" ) // levelPriority is used to map a log level to a @@ -20,11 +21,17 @@ var levelPriority = map[string]gsyslog.Priority{ // writing them to a Syslogger. Implements the io.Writer // interface. type SyslogWrapper struct { - l gsyslog.Syslogger + l gsyslog.Syslogger + filt *logutils.LevelFilter } // Write is used to implement io.Writer func (s *SyslogWrapper) Write(p []byte) (int, error) { + // Skip syslog if the log level doesn't apply + if !s.filt.Check(p) { + return 0, nil + } + // Extract log level var level string afterLevel := p diff --git a/command/agent/syslog_test.go b/command/agent/syslog_test.go new file mode 100644 index 0000000000..f25ec45046 --- /dev/null +++ b/command/agent/syslog_test.go @@ -0,0 +1,35 @@ +package agent + +import ( + "testing" + + "github.com/hashicorp/go-syslog" + "github.com/hashicorp/logutils" +) + +func TestSyslogFilter(t *testing.T) { + l, err := gsyslog.NewLogger(gsyslog.LOG_NOTICE, "LOCAL0", "consul") + if err != nil { + t.Fatalf("err: %s", err) + } + + filt := LevelFilter() + filt.MinLevel = logutils.LogLevel("INFO") + + s := &SyslogWrapper{l, filt} + n, err := s.Write([]byte("[INFO] test")) + if err != nil { + t.Fatalf("err: %s", err) + } + if n == 0 { + t.Fatalf("should have logged") + } + + n, err = s.Write([]byte("[DEBUG] test")) + if err != nil { + t.Fatalf("err: %s", err) + } + if n != 0 { + t.Fatalf("should not have logged") + } +}