logsystem.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package logger
  2. import (
  3. "io"
  4. "log"
  5. "sync/atomic"
  6. )
  7. // LogSystem is implemented by log output devices.
  8. // All methods can be called concurrently from multiple goroutines.
  9. type LogSystem interface {
  10. LogPrint(LogMsg)
  11. }
  12. // NewStdLogSystem creates a LogSystem that prints to the given writer.
  13. // The flag values are defined package log.
  14. func NewStdLogSystem(writer io.Writer, flags int, level LogLevel) *StdLogSystem {
  15. logger := log.New(writer, "", flags)
  16. return &StdLogSystem{logger, uint32(level)}
  17. }
  18. type StdLogSystem struct {
  19. logger *log.Logger
  20. level uint32
  21. }
  22. func (t *StdLogSystem) LogPrint(msg LogMsg) {
  23. stdmsg, ok := msg.(stdMsg)
  24. if ok {
  25. if t.GetLogLevel() >= stdmsg.Level() {
  26. t.logger.Print(stdmsg.String())
  27. }
  28. }
  29. }
  30. func (t *StdLogSystem) SetLogLevel(i LogLevel) {
  31. atomic.StoreUint32(&t.level, uint32(i))
  32. }
  33. func (t *StdLogSystem) GetLogLevel() LogLevel {
  34. return LogLevel(atomic.LoadUint32(&t.level))
  35. }
  36. // NewJSONLogSystem creates a LogSystem that prints to the given writer without
  37. // adding extra information irrespective of loglevel only if message is JSON type
  38. func NewJsonLogSystem(writer io.Writer) LogSystem {
  39. logger := log.New(writer, "", 0)
  40. return &jsonLogSystem{logger}
  41. }
  42. type jsonLogSystem struct {
  43. logger *log.Logger
  44. }
  45. func (t *jsonLogSystem) LogPrint(msg LogMsg) {
  46. jsonmsg, ok := msg.(jsonMsg)
  47. if ok {
  48. t.logger.Print(jsonmsg.String())
  49. }
  50. }