writer.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package logrus
  2. import (
  3. "bufio"
  4. "io"
  5. "runtime"
  6. )
  7. // Writer at INFO level. See WriterLevel for details.
  8. func (logger *Logger) Writer() *io.PipeWriter {
  9. return logger.WriterLevel(InfoLevel)
  10. }
  11. // WriterLevel returns an io.Writer that can be used to write arbitrary text to
  12. // the logger at the given log level. Each line written to the writer will be
  13. // printed in the usual way using formatters and hooks. The writer is part of an
  14. // io.Pipe and it is the callers responsibility to close the writer when done.
  15. // This can be used to override the standard library logger easily.
  16. func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
  17. return NewEntry(logger).WriterLevel(level)
  18. }
  19. func (entry *Entry) Writer() *io.PipeWriter {
  20. return entry.WriterLevel(InfoLevel)
  21. }
  22. func (entry *Entry) WriterLevel(level Level) *io.PipeWriter {
  23. reader, writer := io.Pipe()
  24. var printFunc func(args ...interface{})
  25. switch level {
  26. case TraceLevel:
  27. printFunc = entry.Trace
  28. case DebugLevel:
  29. printFunc = entry.Debug
  30. case InfoLevel:
  31. printFunc = entry.Info
  32. case WarnLevel:
  33. printFunc = entry.Warn
  34. case ErrorLevel:
  35. printFunc = entry.Error
  36. case FatalLevel:
  37. printFunc = entry.Fatal
  38. case PanicLevel:
  39. printFunc = entry.Panic
  40. default:
  41. printFunc = entry.Print
  42. }
  43. go entry.writerScanner(reader, printFunc)
  44. runtime.SetFinalizer(writer, writerFinalizer)
  45. return writer
  46. }
  47. func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
  48. scanner := bufio.NewScanner(reader)
  49. for scanner.Scan() {
  50. printFunc(scanner.Text())
  51. }
  52. if err := scanner.Err(); err != nil {
  53. entry.Errorf("Error while reading from Writer: %s", err)
  54. }
  55. reader.Close()
  56. }
  57. func writerFinalizer(writer *io.PipeWriter) {
  58. writer.Close()
  59. }