

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 6
click for more info
Not enough gems
Cost: 6 gems
1: Logging in Go
incomplete
2: Use the Logger
incomplete
3: Logging Requests
incomplete
4: Global Logger vs. Dependency Injection
incomplete
5: Logger Configuration
incomplete
6: Logger Failure
incomplete
7: Buffered Logging
incomplete
8: Logger Cleanup
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
It's very common to log requests in a web service. One of the cleaner ways to implement this is with a middleware function that logs the request after it's been served:
func requestLogger(logger *log.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
logger.Printf("Wake up babe, a new %s request to %s just dropped", r.Method, r.URL.Path)
})
}
}
This one simply logs the request method and path after the request has been served. Notice that it takes a *log.Logger as an argument, allowing you to use any logger you want on a per-handler basis. So, instead of declaring a handler that we want to log like this:
mux.HandleFunc("POST /api/shorten", apiCfg.handlerShortenURL)
We can use middleware:
mux.Handle("/api/shorten", requestLogger(logger)(http.HandlerFunc(apiCfg.handlerShortenURL)))
Alternatively, we can wrap the entire mux with the middleware, so that all requests are logged:
srv = &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: requestLogger(logger)(mux),
}
Log each served request with middleware.
Served request: METHOD Path
METHOD is the HTTP method of the request, and Path is the path of the request. For example:
Served request: GET /
go run . 2>&1 | sh -c 'trap "" INT; tee linko.out.log'
Run and submit the CLI tests from the root of the Linko repo.