blob: 9e1f7513597d24c03ba25afd911b3d8a733c5c5f [file] [log] [blame]
Jonathan Hartf86817b2018-08-17 10:35:54 -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 {
Matteo Scandolo1f49bf52018-11-20 13:56:45 -080014 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 {
Jonathan Hartf86817b2018-08-17 10:35:54 -070022 reader, writer := io.Pipe()
23
24 var printFunc func(args ...interface{})
Matteo Scandolo1f49bf52018-11-20 13:56:45 -080025
Jonathan Hartf86817b2018-08-17 10:35:54 -070026 switch level {
Matteo Scandolo1f49bf52018-11-20 13:56:45 -080027 case TraceLevel:
28 printFunc = entry.Trace
Jonathan Hartf86817b2018-08-17 10:35:54 -070029 case DebugLevel:
Matteo Scandolo1f49bf52018-11-20 13:56:45 -080030 printFunc = entry.Debug
Jonathan Hartf86817b2018-08-17 10:35:54 -070031 case InfoLevel:
Matteo Scandolo1f49bf52018-11-20 13:56:45 -080032 printFunc = entry.Info
Jonathan Hartf86817b2018-08-17 10:35:54 -070033 case WarnLevel:
Matteo Scandolo1f49bf52018-11-20 13:56:45 -080034 printFunc = entry.Warn
Jonathan Hartf86817b2018-08-17 10:35:54 -070035 case ErrorLevel:
Matteo Scandolo1f49bf52018-11-20 13:56:45 -080036 printFunc = entry.Error
Jonathan Hartf86817b2018-08-17 10:35:54 -070037 case FatalLevel:
Matteo Scandolo1f49bf52018-11-20 13:56:45 -080038 printFunc = entry.Fatal
Jonathan Hartf86817b2018-08-17 10:35:54 -070039 case PanicLevel:
Matteo Scandolo1f49bf52018-11-20 13:56:45 -080040 printFunc = entry.Panic
Jonathan Hartf86817b2018-08-17 10:35:54 -070041 default:
Matteo Scandolo1f49bf52018-11-20 13:56:45 -080042 printFunc = entry.Print
Jonathan Hartf86817b2018-08-17 10:35:54 -070043 }
44
Matteo Scandolo1f49bf52018-11-20 13:56:45 -080045 go entry.writerScanner(reader, printFunc)
Jonathan Hartf86817b2018-08-17 10:35:54 -070046 runtime.SetFinalizer(writer, writerFinalizer)
47
48 return writer
49}
50
Matteo Scandolo1f49bf52018-11-20 13:56:45 -080051func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
Jonathan Hartf86817b2018-08-17 10:35:54 -070052 scanner := bufio.NewScanner(reader)
53 for scanner.Scan() {
54 printFunc(scanner.Text())
55 }
56 if err := scanner.Err(); err != nil {
Matteo Scandolo1f49bf52018-11-20 13:56:45 -080057 entry.Errorf("Error while reading from Writer: %s", err)
Jonathan Hartf86817b2018-08-17 10:35:54 -070058 }
59 reader.Close()
60}
61
62func writerFinalizer(writer *io.PipeWriter) {
63 writer.Close()
64}