blob: 72e8e3a1b65f1cc3fcfff9af1cc7373692a2dde2 [file] [log] [blame]
khenaidooab1f7bd2019-11-14 14:00:27 -05001package logrus
2
3import (
4 "bufio"
5 "io"
6 "runtime"
7)
8
khenaidood948f772021-08-11 17:49:24 -04009// Writer at INFO level. See WriterLevel for details.
khenaidooab1f7bd2019-11-14 14:00:27 -050010func (logger *Logger) Writer() *io.PipeWriter {
11 return logger.WriterLevel(InfoLevel)
12}
13
khenaidood948f772021-08-11 17:49:24 -040014// 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.
khenaidooab1f7bd2019-11-14 14:00:27 -050019func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
20 return NewEntry(logger).WriterLevel(level)
21}
22
23func (entry *Entry) Writer() *io.PipeWriter {
24 return entry.WriterLevel(InfoLevel)
25}
26
27func (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
57func (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
68func writerFinalizer(writer *io.PipeWriter) {
69 writer.Close()
70}