blob: f74d2aa5fc615b047db8ad394eb7bdefd618d2d5 [file] [log] [blame]
David K. Bainbridgeee02c8e2016-11-09 09:13:46 -08001package 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 reader, writer := io.Pipe()
15
16 var printFunc func(args ...interface{})
17 switch level {
18 case DebugLevel:
19 printFunc = logger.Debug
20 case InfoLevel:
21 printFunc = logger.Info
22 case WarnLevel:
23 printFunc = logger.Warn
24 case ErrorLevel:
25 printFunc = logger.Error
26 case FatalLevel:
27 printFunc = logger.Fatal
28 case PanicLevel:
29 printFunc = logger.Panic
30 default:
31 printFunc = logger.Print
32 }
33
34 go logger.writerScanner(reader, printFunc)
35 runtime.SetFinalizer(writer, writerFinalizer)
36
37 return writer
38}
39
40func (logger *Logger) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
41 scanner := bufio.NewScanner(reader)
42 for scanner.Scan() {
43 printFunc(scanner.Text())
44 }
45 if err := scanner.Err(); err != nil {
46 logger.Errorf("Error while reading from Writer: %s", err)
47 }
48 reader.Close()
49}
50
51func writerFinalizer(writer *io.PipeWriter) {
52 writer.Close()
53}