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

Add request id to logs. #4461

Merged
merged 2 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions internal/controlplane/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,9 @@ func (s *Server) StartGRPCServer(ctx context.Context) error {
interceptors := []grpc.UnaryServerInterceptor{
// TODO: this has no test coverage!
util.SanitizingInterceptor(),
// This adds `Grpc-Metadata-Request-Id` to the
// response.
logger.RequestIDInterceptor("request-id"),
logger.Interceptor(s.cfg.LoggingConfig),
TokenValidationInterceptor,
EntityContextProjectInterceptor,
Expand Down
21 changes: 21 additions & 0 deletions internal/logger/logging_interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"path"
"time"

"github.com/google/uuid"
"github.com/rs/zerolog"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
Expand Down Expand Up @@ -101,3 +102,23 @@ func Interceptor(cfg config.LoggingConfig) grpc.UnaryServerInterceptor {
return resp, err
}
}

// RequestIDInterceptor traces request ids.
//
// It's job is to add a request id (UUID) to the context so that all
// subsequent logs inherit it, making it easier to track down problems
// on a per-request basis. It also sends back it back in a header.
func RequestIDInterceptor(headerSuffix string) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
rID := uuid.New().String()
ctx = zerolog.Ctx(ctx).With().Str("request_id", rID).Logger().WithContext(ctx)

resp, err := handler(ctx, req)

if err := grpc.SendHeader(ctx, metadata.Pairs(headerSuffix, rID)); err != nil {
zerolog.Ctx(ctx).Trace().Err(err).Msg("unable to attach request id to trailer")
}

return resp, err
}
}
Loading