英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论