From 1d1fd2d9ce6cca62f9904035ab7cfa56b76c08ef Mon Sep 17 00:00:00 2001 From: Damien Radtke Date: Tue, 1 Mar 2016 17:33:54 -0600 Subject: [PATCH 1/2] Add WriterLevel() function to the logger This commit adds a variant of the logger's Writer() function that accepts a log level. When the variant is used, any messages written to the returned pipe will be written with the provided level. The original Writer() function uses the logger's Print() method as it always has. --- writer.go | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/writer.go b/writer.go index 1e30b1c..5768892 100644 --- a/writer.go +++ b/writer.go @@ -7,18 +7,40 @@ import ( ) func (logger *Logger) Writer() *io.PipeWriter { + return logger.WriterLevel(255) +} + +func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { reader, writer := io.Pipe() - go logger.writerScanner(reader) + var printFunc func(args ...interface{}) + switch level { + case DebugLevel: + printFunc = logger.Debug + case InfoLevel: + printFunc = logger.Info + case WarnLevel: + printFunc = logger.Warn + case ErrorLevel: + printFunc = logger.Error + case FatalLevel: + printFunc = logger.Fatal + case PanicLevel: + printFunc = logger.Panic + default: + printFunc = logger.Print + } + + go logger.writerScanner(reader, printFunc) runtime.SetFinalizer(writer, writerFinalizer) return writer } -func (logger *Logger) writerScanner(reader *io.PipeReader) { +func (logger *Logger) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { scanner := bufio.NewScanner(reader) for scanner.Scan() { - logger.Print(scanner.Text()) + printFunc(scanner.Text()) } if err := scanner.Err(); err != nil { logger.Errorf("Error while reading from Writer: %s", err) From 218981bef407b4a4ed1c6e25a8f86efe39665764 Mon Sep 17 00:00:00 2001 From: Antoine Grondin Date: Sat, 16 Apr 2016 12:46:11 +0530 Subject: [PATCH 2/2] use constant InfoLevel instead of 255 --- writer.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/writer.go b/writer.go index 5768892..f74d2aa 100644 --- a/writer.go +++ b/writer.go @@ -7,7 +7,7 @@ import ( ) func (logger *Logger) Writer() *io.PipeWriter { - return logger.WriterLevel(255) + return logger.WriterLevel(InfoLevel) } func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {