douba5540
douba5540
2014-01-08 05:34

如何为http.ListenAndServe设置访问/错误日志

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答
已采纳

I am using the following for a simple server. I am wondering how to setup an access log for all the requests logging the timestamp, method, request url and the http response code.

http.HandleFunc("/foo", funcFoo)
err := http.ListenAndServe("127.0.0.1:2074", nil)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongyiba8082 dongyiba8082 7年前

    Take a look here: http://github.com/gorilla/handlers

    http.Handle("/foo", funcFoo)
    err := http.ListenAndServe("127.0.0.1:2074", handlers.LoggingHandler(os.Stdout, http.DefaultServeMux))
    

    This will log any incoming connections across the whole server. os.Stdout can be replaced by anything that provides an io.Writer (i.e. a file, a HTTP stream, etc). If you want it to be per-route, you can do:

    http.Handle("/foo", handlers.LoggingHandler(os.Stdout, funcFoo))
    

    It will also work with gorilla/mux and other routers/frameworks that are http.Handler compatible.

    点赞 评论 复制链接分享

为你推荐