Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include trace in every log #38

Open
Mistic92 opened this issue Apr 8, 2021 · 1 comment
Open

Include trace in every log #38

Mistic92 opened this issue Apr 8, 2021 · 1 comment

Comments

@Mistic92
Copy link

Mistic92 commented Apr 8, 2021

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
Copy link

amammay commented Aug 17, 2021

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants