writer.go 1.3 KB

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