writer.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package logrus
  2. import (
  3. "bufio"
  4. "io"
  5. "runtime"
  6. )
  7. func (logger *Logger) Writer() *io.PipeWriter {
  8. return logger.WriterLevel(InfoLevel)
  9. }
  10. func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
  11. reader, writer := io.Pipe()
  12. var printFunc func(args ...interface{})
  13. switch level {
  14. case DebugLevel:
  15. printFunc = logger.Debug
  16. case InfoLevel:
  17. printFunc = logger.Info
  18. case WarnLevel:
  19. printFunc = logger.Warn
  20. case ErrorLevel:
  21. printFunc = logger.Error
  22. case FatalLevel:
  23. printFunc = logger.Fatal
  24. case PanicLevel:
  25. printFunc = logger.Panic
  26. default:
  27. printFunc = logger.Print
  28. }
  29. go logger.writerScanner(reader, printFunc)
  30. runtime.SetFinalizer(writer, writerFinalizer)
  31. return writer
  32. }
  33. func (logger *Logger) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
  34. scanner := bufio.NewScanner(reader)
  35. for scanner.Scan() {
  36. printFunc(scanner.Text())
  37. }
  38. if err := scanner.Err(); err != nil {
  39. logger.Errorf("Error while reading from Writer: %s", err)
  40. }
  41. reader.Close()
  42. }
  43. func writerFinalizer(writer *io.PipeWriter) {
  44. writer.Close()
  45. }