Logger

该中间件负责打印各个请求和响应日志.

代码如:

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "net/http"
  6.  
  7. "github.com/urfave/negroni"
  8. )
  9.  
  10. func main() {
  11. mux := http.NewServeMux()
  12. mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
  13. fmt.Fprintf(w, "Welcome to the home page!")
  14. })
  15.  
  16. n := negroni.New()
  17. n.Use(negroni.NewLogger())
  18. n.UseHandler(mux)
  19.  
  20. http.ListenAndServe(":3004", n)
  21. }

每个请求打印日志将如下:

  1. [negroni] 2017-10-04T14:56:25+02:00 | 200 | 378µs | localhost:3004 | GET /

当然你可以调用 SetFormat 来自定义日志的格式。格式是一个预定义了字段的 LoggerEntry 结构体。正如以下代码: -

  1. l.SetFormat("[{{.Status}} {{.Duration}}] - {{.Request.UserAgent}}")