Logger
该中间件负责打印各个请求和响应日志.
代码如:
- package main
- import (
- "fmt"
- "net/http"
- "github.com/urfave/negroni"
- )
- func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
- fmt.Fprintf(w, "Welcome to the home page!")
- })
- n := negroni.New()
- n.Use(negroni.NewLogger())
- n.UseHandler(mux)
- http.ListenAndServe(":3004", n)
- }
每个请求打印日志将如下:
[negroni] 2017-10-04T14:56:25+02:00 | 200 | 378µs | localhost:3004 | GET /
当然你可以调用 SetFormat 来自定义日志的格式。格式是一个预定义了字段的 LoggerEntry 结构体。正如以下代码: -
l.SetFormat("[{{.Status}} {{.Duration}}] - {{.Request.UserAgent}}")