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

huangapple go评论90阅读模式
英文:

how to setup access/error log for http.ListenAndServe

问题

我正在使用以下代码来创建一个简单的服务器。我想知道如何设置访问日志,记录时间戳、请求方法、请求URL和HTTP响应代码。

http.HandleFunc("/foo", funcFoo)
err := http.ListenAndServe("127.0.0.1:2074", nil)
英文:

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

得分: 33

请看这里:http://github.com/gorilla/handlers

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

这将记录整个服务器上的所有传入连接。os.Stdout 可以被任何提供 io.Writer 的东西替换(例如文件、HTTP 流等)。如果你想要每个路由都有日志记录,可以这样做:

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

它也适用于 gorilla/mux 和其他与 http.Handler 兼容的路由器/框架。

英文:

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.

huangapple
  • 本文由 发表于 2014年1月8日 13:34:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/20987752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定