writer.go 1.2 KB

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