blob: 7bdebedc60bb91b7c24ec373cace3c6d3e9365a7 [file] [log] [blame]
David K. Bainbridge215e0242017-09-05 23:18:24 -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 DebugLevel:
28 printFunc = entry.Debug
29 case InfoLevel:
30 printFunc = entry.Info
31 case WarnLevel:
32 printFunc = entry.Warn
33 case ErrorLevel:
34 printFunc = entry.Error
35 case FatalLevel:
36 printFunc = entry.Fatal
37 case PanicLevel:
38 printFunc = entry.Panic
39 default:
40 printFunc = entry.Print
41 }
42
43 go entry.writerScanner(reader, printFunc)
44 runtime.SetFinalizer(writer, writerFinalizer)
45
46 return writer
47}
48
49func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
50 scanner := bufio.NewScanner(reader)
51 for scanner.Scan() {
52 printFunc(scanner.Text())
53 }
54 if err := scanner.Err(); err != nil {
55 entry.Errorf("Error while reading from Writer: %s", err)
56 }
57 reader.Close()
58}
59
60func writerFinalizer(writer *io.PipeWriter) {
61 writer.Close()
62}