David K. Bainbridge | ee02c8e | 2016-11-09 09:13:46 -0800 | [diff] [blame^] | 1 | package logrus |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "io" |
| 6 | "runtime" |
| 7 | ) |
| 8 | |
| 9 | func (logger *Logger) Writer() *io.PipeWriter { |
| 10 | return logger.WriterLevel(InfoLevel) |
| 11 | } |
| 12 | |
| 13 | func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { |
| 14 | reader, writer := io.Pipe() |
| 15 | |
| 16 | var printFunc func(args ...interface{}) |
| 17 | switch level { |
| 18 | case DebugLevel: |
| 19 | printFunc = logger.Debug |
| 20 | case InfoLevel: |
| 21 | printFunc = logger.Info |
| 22 | case WarnLevel: |
| 23 | printFunc = logger.Warn |
| 24 | case ErrorLevel: |
| 25 | printFunc = logger.Error |
| 26 | case FatalLevel: |
| 27 | printFunc = logger.Fatal |
| 28 | case PanicLevel: |
| 29 | printFunc = logger.Panic |
| 30 | default: |
| 31 | printFunc = logger.Print |
| 32 | } |
| 33 | |
| 34 | go logger.writerScanner(reader, printFunc) |
| 35 | runtime.SetFinalizer(writer, writerFinalizer) |
| 36 | |
| 37 | return writer |
| 38 | } |
| 39 | |
| 40 | func (logger *Logger) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { |
| 41 | scanner := bufio.NewScanner(reader) |
| 42 | for scanner.Scan() { |
| 43 | printFunc(scanner.Text()) |
| 44 | } |
| 45 | if err := scanner.Err(); err != nil { |
| 46 | logger.Errorf("Error while reading from Writer: %s", err) |
| 47 | } |
| 48 | reader.Close() |
| 49 | } |
| 50 | |
| 51 | func writerFinalizer(writer *io.PipeWriter) { |
| 52 | writer.Close() |
| 53 | } |