另客网go项目公用的代码库

writer.go 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. }