Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [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 | return NewEntry(logger).WriterLevel(level) |
| 15 | } |
| 16 | |
| 17 | func (entry *Entry) Writer() *io.PipeWriter { |
| 18 | return entry.WriterLevel(InfoLevel) |
| 19 | } |
| 20 | |
| 21 | func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { |
| 22 | reader, writer := io.Pipe() |
| 23 | |
| 24 | var printFunc func(args ...interface{}) |
| 25 | |
| 26 | switch level { |
| 27 | case TraceLevel: |
| 28 | printFunc = entry.Trace |
| 29 | case DebugLevel: |
| 30 | printFunc = entry.Debug |
| 31 | case InfoLevel: |
| 32 | printFunc = entry.Info |
| 33 | case WarnLevel: |
| 34 | printFunc = entry.Warn |
| 35 | case ErrorLevel: |
| 36 | printFunc = entry.Error |
| 37 | case FatalLevel: |
| 38 | printFunc = entry.Fatal |
| 39 | case PanicLevel: |
| 40 | printFunc = entry.Panic |
| 41 | default: |
| 42 | printFunc = entry.Print |
| 43 | } |
| 44 | |
| 45 | go entry.writerScanner(reader, printFunc) |
| 46 | runtime.SetFinalizer(writer, writerFinalizer) |
| 47 | |
| 48 | return writer |
| 49 | } |
| 50 | |
| 51 | func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { |
| 52 | scanner := bufio.NewScanner(reader) |
| 53 | for scanner.Scan() { |
| 54 | printFunc(scanner.Text()) |
| 55 | } |
| 56 | if err := scanner.Err(); err != nil { |
| 57 | entry.Errorf("Error while reading from Writer: %s", err) |
| 58 | } |
| 59 | reader.Close() |
| 60 | } |
| 61 | |
| 62 | func writerFinalizer(writer *io.PipeWriter) { |
| 63 | writer.Close() |
| 64 | } |