Golang : How to log each HTTP request to your web server?
Problem:
You want to log each HTTP request made to your web server complete with duration (start time - end time), requester IP address, URI accessed and you also want to save the log messages into a file for viewing later.
How to do that?
NOTE: Saving HTTP requests log to file can be useful for troubleshooting purpose or assist in identifying attackers on your server. However, do take note that the log's file size will grow and needs to be rolled-over from time to time to keep the filesize from taking up all the disk space.
Solution:
Create a request logger function and wrap it on the HTTP request multiplexer.
Here you go!
package main
import (
"log"
"net/http"
"os"
"time"
)
func RequestLogger(targetMux http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
targetMux.ServeHTTP(w, r)
// log request by who(IP address)
requesterIP := r.RemoteAddr
log.Printf(
"%s\t\t%s\t\t%s\t\t%v",
r.Method,
r.RequestURI,
requesterIP,
time.Since(start),
)
})
}
func SayGoodByeWorld(w http.ResponseWriter, r *http.Request) {
html := "Good Bye World"
w.Write([]byte(html))
}
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
html := "Hello World"
w.Write([]byte(html))
}
func main() {
fileName := "webrequests.log"
// https://www.socketloop.com/tutorials/golang-how-to-save-log-messages-to-file
logFile, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
defer logFile.Close()
// direct all log messages to webrequests.log
log.SetOutput(logFile)
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
mux.HandleFunc("/bye", SayGoodByeWorld)
http.ListenAndServe(":8080", RequestLogger(mux))
}
Build and run the program above.
Point your browser to
localhost:8080
andlocalhost:8080/bye
See the content of
webrequests.log
References:
https://www.socketloop.com/tutorials/golang-how-to-save-log-messages-to-file
https://www.socketloop.com/tutorials/create-file-golang
https://stackoverflow.com/questions/26184465/go-add-logging-to-each-router
See also : Golang : Routes multiplexer routing example with regular expression control
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.4k How to check with curl if my website or the asset is gzipped ?
+14.4k Golang : How to filter a map's elements for faster lookup
+10.5k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+27.5k Golang : dial tcp: too many colons in address
+11.1k Golang : Web routing/multiplex example
+14.3k Golang : Simple word wrap or line breaking example
+17.6k Golang : [json: cannot unmarshal object into Go value of type]
+5.8k Unix/Linux : How to test user agents blocked successfully ?
+9.1k Golang : Serving HTTP and Websocket from different ports in a program example
+21.4k Curl usage examples with Golang
+20.7k Golang : Read directory content with os.Open
+15.3k Golang : Get all local users and print out their home directory, description and group id