khenaidoo | ab1f7bd | 2019-11-14 14:00:27 -0500 | [diff] [blame] | 1 | package logrus |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "io" |
| 6 | "runtime" |
| 7 | ) |
| 8 | |
khenaidoo | d948f77 | 2021-08-11 17:49:24 -0400 | [diff] [blame] | 9 | // Writer at INFO level. See WriterLevel for details. |
khenaidoo | ab1f7bd | 2019-11-14 14:00:27 -0500 | [diff] [blame] | 10 | func (logger *Logger) Writer() *io.PipeWriter { |
| 11 | return logger.WriterLevel(InfoLevel) |
| 12 | } |
| 13 | |
khenaidoo | d948f77 | 2021-08-11 17:49:24 -0400 | [diff] [blame] | 14 | // WriterLevel returns an io.Writer that can be used to write arbitrary text to |
| 15 | // the logger at the given log level. Each line written to the writer will be |
| 16 | // printed in the usual way using formatters and hooks. The writer is part of an |
| 17 | // io.Pipe and it is the callers responsibility to close the writer when done. |
| 18 | // This can be used to override the standard library logger easily. |
khenaidoo | ab1f7bd | 2019-11-14 14:00:27 -0500 | [diff] [blame] | 19 | func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { |
| 20 | return NewEntry(logger).WriterLevel(level) |
| 21 | } |
| 22 | |
| 23 | func (entry *Entry) Writer() *io.PipeWriter { |
| 24 | return entry.WriterLevel(InfoLevel) |
| 25 | } |
| 26 | |
| 27 | func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { |
| 28 | reader, writer := io.Pipe() |
| 29 | |
| 30 | var printFunc func(args ...interface{}) |
| 31 | |
| 32 | switch level { |
| 33 | case TraceLevel: |
| 34 | printFunc = entry.Trace |
| 35 | case DebugLevel: |
| 36 | printFunc = entry.Debug |
| 37 | case InfoLevel: |
| 38 | printFunc = entry.Info |
| 39 | case WarnLevel: |
| 40 | printFunc = entry.Warn |
| 41 | case ErrorLevel: |
| 42 | printFunc = entry.Error |
| 43 | case FatalLevel: |
| 44 | printFunc = entry.Fatal |
| 45 | case PanicLevel: |
| 46 | printFunc = entry.Panic |
| 47 | default: |
| 48 | printFunc = entry.Print |
| 49 | } |
| 50 | |
| 51 | go entry.writerScanner(reader, printFunc) |
| 52 | runtime.SetFinalizer(writer, writerFinalizer) |
| 53 | |
| 54 | return writer |
| 55 | } |
| 56 | |
| 57 | func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { |
| 58 | scanner := bufio.NewScanner(reader) |
| 59 | for scanner.Scan() { |
| 60 | printFunc(scanner.Text()) |
| 61 | } |
| 62 | if err := scanner.Err(); err != nil { |
| 63 | entry.Errorf("Error while reading from Writer: %s", err) |
| 64 | } |
| 65 | reader.Close() |
| 66 | } |
| 67 | |
| 68 | func writerFinalizer(writer *io.PipeWriter) { |
| 69 | writer.Close() |
| 70 | } |