ram_mohan
(Ram Mohan)
September 10, 2019, 5:27am
1
Is there a way to log all the related logs with some context. say some unique ID for that session/request.
HTTP handle Function may call some other common functions (which may be call by other Handler functions) and all those function logs should have this unique ID to relate all the logs of that session.
2 Likes
NobbZ
(Norbert Melzer)
September 10, 2019, 5:32am
2
We have some HTTP tool at work that does exactly that.
I recall we use zap
for logging and “derive” a new logger using With()
which is then injected into a request context.
I will extract the relevant code path for you once I can access the VPN.
2 Likes
ram_mohan
(Ram Mohan)
September 10, 2019, 6:40am
3
Great, will be waiting for your reply
2 Likes
NobbZ
(Norbert Melzer)
September 10, 2019, 7:10am
4
Sorry to leave you waiting, I still can’t access our companies VPN due to some firmware update on our firewalls. If our IT departement doesn’t fix that in the next 2 hours I’ll have to do an office day rather than remote. So I think I should be able to post our solution to that problem in ~4 hours or sooner.
3 Likes
NobbZ
(Norbert Melzer)
September 10, 2019, 10:04am
5
Its basically this:
package service
import (
"net/http"
"sync"
"time"
"go.uber.org/zap"
)
type HandleFunc func(*zap.Logger, http.ResponseWriter, *http.Request)
type Handler struct {
f HandleFunc
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rid := requestID()
logger := zap.L().With(zap.String("request_url", r.RequestURI), zap.Int64("request_id", rid), zap.String("method", r.Method))
logger.Info("Received request")
start := time.Now()
h.f(logger, w, r)
duration := time.Since(start)
logger.Info("Finished request", zap.Duration("duration", duration))
}
func NewHandler(f HandleFunc) *Handler {
return &Handler{f: f}
}
And then we use it like this:
http.Handle("/foo", service.NewHandler(service.Foo))
zap.L().Panic("HTTP server crashed", zap.Error(http.ListenAndServe(addr, nil)))
2 Likes
ram_mohan
(Ram Mohan)
September 11, 2019, 10:22am
6
I am using mux and handlers for routing and CORS, is there any way we can pass on this logger to those handlers?
looks like we are overriding HandleFunc and Handler here in this example.
2 Likes
NobbZ
(Norbert Melzer)
September 11, 2019, 11:04am
7
Sorry, we are not using mux, in our case it’s just 2 endpoints that needed to be served and that way was a suitable workaround.
You need to check whether or not you can use a similar technic with mux.
2 Likes
ram_mohan
(Ram Mohan)
September 12, 2019, 4:41am
8
Thanks a lot. i will figure it out. and post if a find one.
3 Likes
system
(system)
Closed
December 11, 2019, 4:41am
9
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.