logrus/writer.go

65 lines
1.3 KiB
Go
Raw Normal View History

2015-01-26 17:59:50 +03:00
package logrus
import (
"bufio"
"io"
"runtime"
)
2015-03-10 19:06:14 +03:00
func (logger *Logger) Writer() *io.PipeWriter {
2016-04-16 10:16:11 +03:00
return logger.WriterLevel(InfoLevel)
}
func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
return NewEntry(logger).WriterLevel(level)
}
func (entry *Entry) Writer() *io.PipeWriter {
return entry.WriterLevel(InfoLevel)
}
func (entry *Entry) WriterLevel(level Level) *io.PipeWriter {
2015-01-26 17:59:50 +03:00
reader, writer := io.Pipe()
var printFunc func(args ...interface{})
switch level {
2017-10-20 15:40:54 +03:00
case TraceLevel:
printFunc = entry.Trace
case DebugLevel:
printFunc = entry.Debug
case InfoLevel:
printFunc = entry.Info
case WarnLevel:
printFunc = entry.Warn
case ErrorLevel:
printFunc = entry.Error
case FatalLevel:
printFunc = entry.Fatal
case PanicLevel:
printFunc = entry.Panic
default:
printFunc = entry.Print
}
go entry.writerScanner(reader, printFunc)
2015-01-26 17:59:50 +03:00
runtime.SetFinalizer(writer, writerFinalizer)
return writer
}
func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
2015-01-26 17:59:50 +03:00
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
printFunc(scanner.Text())
2015-01-26 17:59:50 +03:00
}
if err := scanner.Err(); err != nil {
entry.Errorf("Error while reading from Writer: %s", err)
2015-01-26 17:59:50 +03:00
}
reader.Close()
}
func writerFinalizer(writer *io.PipeWriter) {
writer.Close()
}