2015-09-10 00:51:03 -04:00
|
|
|
package logrus
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"io"
|
|
|
|
"runtime"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (logger *Logger) Writer() *io.PipeWriter {
|
2016-07-14 17:59:20 -04:00
|
|
|
return logger.WriterLevel(InfoLevel)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
|
2015-09-10 00:51:03 -04:00
|
|
|
reader, writer := io.Pipe()
|
|
|
|
|
2016-07-14 17:59:20 -04:00
|
|
|
var printFunc func(args ...interface{})
|
|
|
|
switch level {
|
|
|
|
case DebugLevel:
|
|
|
|
printFunc = logger.Debug
|
|
|
|
case InfoLevel:
|
|
|
|
printFunc = logger.Info
|
|
|
|
case WarnLevel:
|
|
|
|
printFunc = logger.Warn
|
|
|
|
case ErrorLevel:
|
|
|
|
printFunc = logger.Error
|
|
|
|
case FatalLevel:
|
|
|
|
printFunc = logger.Fatal
|
|
|
|
case PanicLevel:
|
|
|
|
printFunc = logger.Panic
|
|
|
|
default:
|
|
|
|
printFunc = logger.Print
|
|
|
|
}
|
|
|
|
|
|
|
|
go logger.writerScanner(reader, printFunc)
|
2015-09-10 00:51:03 -04:00
|
|
|
runtime.SetFinalizer(writer, writerFinalizer)
|
|
|
|
|
|
|
|
return writer
|
|
|
|
}
|
|
|
|
|
2016-07-14 17:59:20 -04:00
|
|
|
func (logger *Logger) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
|
2015-09-10 00:51:03 -04:00
|
|
|
scanner := bufio.NewScanner(reader)
|
|
|
|
for scanner.Scan() {
|
2016-07-14 17:59:20 -04:00
|
|
|
printFunc(scanner.Text())
|
2015-09-10 00:51:03 -04:00
|
|
|
}
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
|
|
logger.Errorf("Error while reading from Writer: %s", err)
|
|
|
|
}
|
|
|
|
reader.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func writerFinalizer(writer *io.PipeWriter) {
|
|
|
|
writer.Close()
|
|
|
|
}
|