dongwei5794 2014-10-03 18:15
浏览 45
已采纳

转到:将日志记录添加到每个路由器

Go : add logging to each router

I want to log all my network request in Go web app.

Something like negroni:

// https://github.com/codegangsta/negroni/blob/master/logger.go
// NewLogger returns a new Logger instance
func NewLogger() *Logger {
  return &Logger{log.New(os.Stdout, "[negroni] ", 0)}
}

func (l *Logger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
  start := time.Now()
  l.Printf("Started %s %s", r.Method, r.URL.Path)

  next(rw, r)

  res := rw.(ResponseWriter)
  l.Printf("Completed %v %s in %v", res.Status(), http.StatusText(res.Status()), time.Since(start))
}

So here's my code:

router := httprouter.New()

handler := func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  type Page struct {
    Title string
  }
  tp := template.Must(template.ParseFiles("templates/main.html", "templates/base.html"))
  err := tp.ExecuteTemplate(w, "base", &Page{Title: "AAA"})
  if err != nil {
    log.Fatal(err)
}

router.Handle("GET", "/", handler)

l := log.New(os.Stdout, "[AAA] ", 0)
l.Printf("Listening 0.0.0.0%s", PORT)

l.Fatal(http.ListenAndServe(PORT, router))

If I want to do this, I have to add start := time.Now() and time.Since(start) manually to each router in my code.package main

I think I should wrap it and use interface but don't know how to get started.

How do I implement one simple logging interface and apply all the routed handlers so that I can debug with all the loggings...

Negroni does like:

router := mux.NewRouter()
router.HandleFunc("/", HomeHandler)

n := negroni.New(Middleware1, Middleware2)
// Or use a middleware with the Use() function
n.Use(Middleware3)
// router goes last
n.UseHandler(router)

n.Run(":3000")
  • 写回答

3条回答 默认 最新

  • duanbiao4025 2014-10-03 18:24
    关注

    Wrap the root handler with a handler that logs and delegates to another handler:

     type RequestLogger struct {
         h http.Handler
         l *Logger
     }
    
     func (rl RequestLogger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
         start := time.Now()
         rl.l.Printf("Started %s %s", r.Method, r.URL.Path)
         rl.h.ServeHTTP(w, r)
         rl.l.Printf("Completed %s %s in %v", r.Method, r.URL.Path, time.Since(start))
     }
    
     ---
    
     l := log.New(os.Stdout, "[AAA] ", 0)
     l.Printf("Listening 0.0.0.0%s", PORT)
     l.Fatal(http.ListenAndServe(PORT, RequestLogger{h:router, l:l}))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面