Include trace in every log
Opened this issue · 1 comments
Mistic92 commented
Hi, is there a way to include traceId for every log? I'm using gin with otel and trying to figure out how to approach this issue
amammay commented
@Mistic92 just was browsing through and i ended up doing something like this
func (i *AppLogger) WrapTraceContext(ctx context.Context) *zap.SugaredLogger {
sc := trace.SpanContextFromContext(ctx)
fields := zapdriver.TraceContext(sc.TraceID().String(), sc.SpanID().String(), sc.IsSampled(), i.projectID)
setFields := i.zap.With(fields...)
return setFields.Sugar()
}
and then used it like so
func (s *server) handleGetDog(dogService *gotoproduction.DogService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logger := s.appLogger.WrapTraceContext(ctx)
vars := mux.Vars(r)
dogID, ok := vars["dogID"]
logger.Infof("searching for dog %s", dogID)
if !ok {
s.respond(w, nil, http.StatusBadRequest)
return
}
dog, err := dogService.GetDogByID(ctx, dogID)
if err == gotoproduction.ErrDogNotFound {
s.respond(w, nil, http.StatusNotFound)
return
}
if err != nil {
s.respond(w, nil, http.StatusInternalServerError)
return
}
logger.Infof("search found dog: %s", dog.ID)
s.respond(w, dog, http.StatusOK)
}
}
my full reference is in this repo. https://github.com/amammay/gotoproduction