github.com/volatiletech/authboss@v2.4.1+incompatible/logger.go (about) 1 package authboss 2 3 import ( 4 "context" 5 "fmt" 6 "net/http" 7 ) 8 9 // Logger is the basic logging structure that's required 10 type Logger interface { 11 Info(string) 12 Error(string) 13 } 14 15 // ContextLogger creates a logger from a request context 16 type ContextLogger interface { 17 FromContext(context.Context) Logger 18 } 19 20 // RequestLogger creates a logger from a request 21 type RequestLogger interface { 22 FromRequest(*http.Request) Logger 23 } 24 25 // RequestLogger returns a request logger if possible, if not 26 // it calls Logger which tries to do a ContextLogger, and if 27 // that fails it will finally get a normal logger. 28 func (a *Authboss) RequestLogger(r *http.Request) FmtLogger { 29 logger := a.Config.Core.Logger 30 if reqLogger, ok := logger.(RequestLogger); ok { 31 return FmtLogger{reqLogger.FromRequest(r)} 32 } 33 34 return FmtLogger{a.Logger(r.Context())} 35 } 36 37 // Logger returns an appopriate logger for the context: 38 // If context is nil, then it simply returns the configured 39 // logger. 40 // If context is not nil, then it will attempt to upgrade 41 // the configured logger to a ContextLogger, and create 42 // a context-specific logger for use. 43 func (a *Authboss) Logger(ctx context.Context) FmtLogger { 44 logger := a.Config.Core.Logger 45 if ctx == nil { 46 return FmtLogger{logger} 47 } 48 49 ctxLogger, ok := logger.(ContextLogger) 50 if !ok { 51 return FmtLogger{logger} 52 } 53 54 return FmtLogger{ctxLogger.FromContext(ctx)} 55 } 56 57 // FmtLogger adds convenience functions on top of the logging 58 // methods for formatting. 59 type FmtLogger struct { 60 Logger 61 } 62 63 // Errorf prints to Error() with fmt.Printf semantics 64 func (f FmtLogger) Errorf(format string, values ...interface{}) { 65 f.Logger.Error(fmt.Sprintf(format, values...)) 66 } 67 68 // Infof prints to Info() with fmt.Printf semantics 69 func (f FmtLogger) Infof(format string, values ...interface{}) { 70 f.Logger.Info(fmt.Sprintf(format, values...)) 71 }