blob: 9e1f7513597d24c03ba25afd911b3d8a733c5c5f [file] [log] [blame]
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -07001package logrus
2
3import (
4 "bufio"
5 "io"
6 "runtime"
7)
8
9func (logger *Logger) Writer() *io.PipeWriter {
10 return logger.WriterLevel(InfoLevel)
11}
12
13func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
14 return NewEntry(logger).WriterLevel(level)
15}
16
17func (entry *Entry) Writer() *io.PipeWriter {
18 return entry.WriterLevel(InfoLevel)
19}
20
21func (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
51func (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
62func writerFinalizer(writer *io.PipeWriter) {
63 writer.Close()
64}