manager.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package logger
  2. import "sync"
  3. // SharedWriteManager is a package level variable to allows multiple loggers to use the same write manager.
  4. // This is useful when multiple loggers will write to the same file to ensure they don't clobber each other.
  5. var SharedWriteManager = NewWriteManager()
  6. type writeData struct {
  7. target LogOutput
  8. data []byte
  9. }
  10. // WriteManager is a logging service that handles managing multiple writing streams
  11. type WriteManager struct {
  12. shutdown chan struct{}
  13. writeChan chan writeData
  14. writers map[string]Service
  15. wg sync.WaitGroup
  16. }
  17. // NewWriteManager creates a write manager that implements OutputManager
  18. func NewWriteManager() OutputManager {
  19. m := &WriteManager{
  20. shutdown: make(chan struct{}),
  21. writeChan: make(chan writeData, 1000),
  22. }
  23. go m.run()
  24. return m
  25. }
  26. // Append adds a message to the writer runloop
  27. func (m *WriteManager) Append(data []byte, target LogOutput) {
  28. m.wg.Add(1)
  29. m.writeChan <- writeData{data: data, target: target}
  30. }
  31. // Shutdown stops the sync manager service
  32. func (m *WriteManager) Shutdown() {
  33. m.wg.Wait()
  34. close(m.shutdown)
  35. close(m.writeChan)
  36. }
  37. // run is the main runloop that schedules log messages
  38. func (m *WriteManager) run() {
  39. for {
  40. select {
  41. case event, ok := <-m.writeChan:
  42. if ok {
  43. event.target.WriteLogLine(event.data)
  44. m.wg.Done()
  45. }
  46. case <-m.shutdown:
  47. return
  48. }
  49. }
  50. }