Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to setup access/error log for http.ListenAndServe

Tags:

go

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)
like image 873
vrtx54234 Avatar asked Jan 08 '14 05:01

vrtx54234


1 Answers

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.

like image 128
elithrar Avatar answered Nov 07 '22 05:11

elithrar