Skip to content

Instantly share code, notes, and snippets.

@hoitomt
Created January 30, 2015 12:56
Show Gist options
  • Save hoitomt/c0663af8c9443f2a8294 to your computer and use it in GitHub Desktop.
Save hoitomt/c0663af8c9443f2a8294 to your computer and use it in GitHub Desktop.
Golang: Log HTTP Requests in Go
package main
import (
"fmt"
"log"
"net/http"
"os"
)
func main() {
logPath := "development.log"
httpPort := 4000
openLogFile(logPath)
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
http.HandleFunc("/", rootHandler)
fmt.Printf("listening on %v\n", httpPort)
fmt.Printf("Logging to %v\n", logPath)
err := http.ListenAndServe(fmt.Sprintf(":%d", httpPort), logRequest(http.DefaultServeMux))
if err != nil {
log.Fatal(err)
}
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>Hello World</h1><div>Welcome to whereever you are</div>")
}
func logRequest(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func openLogFile(logfile string) {
if logfile != "" {
lf, err := os.OpenFile(logfile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
if err != nil {
log.Fatal("OpenLogfile: os.OpenFile:", err)
}
log.SetOutput(lf)
}
}
@rjterradillos
Copy link

Thanks!

@arl
Copy link

arl commented Dec 16, 2022

Check out this package if you want to log all requests made to your HTTP server. It's a middleware and with it you can log path, status code, body size. github.com/felixge/httpsnoop

@guilherme-guiga
Copy link

Thank u!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment