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条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮