github.com/jxgolibs/go-oauth2-server@v1.0.1/util/response/logging.go (about) 1 package response 2 3 import ( 4 "fmt" 5 "log" 6 "net/http" 7 "os" 8 "time" 9 10 thelog "github.com/RichardKnop/go-oauth2-server/log" 11 "github.com/urfave/negroni" 12 ) 13 14 // Logger is a middleware handler that logs the request as it goes in and the response as it goes out. 15 type Logger struct { 16 // Logger inherits from log.Logger used to log messages with the Logger middleware 17 *log.Logger 18 } 19 20 // NewURLLogger returns a new Logger instance 21 func NewURLLogger() *Logger { 22 return &Logger{log.New(os.Stdout, "[negroni] ", 0)} 23 } 24 25 func (l *Logger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { 26 start := time.Now() 27 ip := r.RemoteAddr 28 if xff := r.Header.Get("X-Forwarded-For"); xff != "" { 29 ip = xff 30 } 31 32 thelog.INFO.Printf("Started %s %s for %s", r.Method, r.URL.Path, ip) 33 34 next(rw, r) 35 36 res := rw.(negroni.ResponseWriter) 37 38 msg := fmt.Sprintf("Finished %s %s : %v %s in %v", r.Method, r.URL.Path, res.Status(), http.StatusText(res.Status()), time.Since(start)) 39 40 switch { 41 case res.Status() < 400: 42 thelog.INFO.Print(msg) 43 case res.Status() < 500: 44 thelog.WARNING.Print(msg) 45 default: 46 thelog.ERROR.Print(msg) 47 } 48 }