logger.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package logger
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "log"
  7. "os"
  8. )
  9. // Logger matches newrelic.Logger to allow implementations to be passed to
  10. // internal packages.
  11. type Logger interface {
  12. Error(msg string, context map[string]interface{})
  13. Warn(msg string, context map[string]interface{})
  14. Info(msg string, context map[string]interface{})
  15. Debug(msg string, context map[string]interface{})
  16. DebugEnabled() bool
  17. }
  18. // ShimLogger implements Logger and does nothing.
  19. type ShimLogger struct{}
  20. // Error allows ShimLogger to implement Logger.
  21. func (s ShimLogger) Error(string, map[string]interface{}) {}
  22. // Warn allows ShimLogger to implement Logger.
  23. func (s ShimLogger) Warn(string, map[string]interface{}) {}
  24. // Info allows ShimLogger to implement Logger.
  25. func (s ShimLogger) Info(string, map[string]interface{}) {}
  26. // Debug allows ShimLogger to implement Logger.
  27. func (s ShimLogger) Debug(string, map[string]interface{}) {}
  28. // DebugEnabled allows ShimLogger to implement Logger.
  29. func (s ShimLogger) DebugEnabled() bool { return false }
  30. type logFile struct {
  31. l *log.Logger
  32. doDebug bool
  33. }
  34. // New creates a basic Logger.
  35. func New(w io.Writer, doDebug bool) Logger {
  36. return &logFile{
  37. l: log.New(w, logPid, logFlags),
  38. doDebug: doDebug,
  39. }
  40. }
  41. const logFlags = log.Ldate | log.Ltime | log.Lmicroseconds
  42. var (
  43. logPid = fmt.Sprintf("(%d) ", os.Getpid())
  44. )
  45. func (f *logFile) fire(level, msg string, ctx map[string]interface{}) {
  46. js, err := json.Marshal(struct {
  47. Level string `json:"level"`
  48. Event string `json:"msg"`
  49. Context map[string]interface{} `json:"context"`
  50. }{
  51. level,
  52. msg,
  53. ctx,
  54. })
  55. if nil == err {
  56. f.l.Printf(string(js))
  57. } else {
  58. f.l.Printf("unable to marshal log entry: %v", err)
  59. }
  60. }
  61. func (f *logFile) Error(msg string, ctx map[string]interface{}) {
  62. f.fire("error", msg, ctx)
  63. }
  64. func (f *logFile) Warn(msg string, ctx map[string]interface{}) {
  65. f.fire("warn", msg, ctx)
  66. }
  67. func (f *logFile) Info(msg string, ctx map[string]interface{}) {
  68. f.fire("info", msg, ctx)
  69. }
  70. func (f *logFile) Debug(msg string, ctx map[string]interface{}) {
  71. if f.doDebug {
  72. f.fire("debug", msg, ctx)
  73. }
  74. }
  75. func (f *logFile) DebugEnabled() bool { return f.doDebug }