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