Skip to content

Adding Context to SpanNameFunc #47

@pquerna

Description

@pquerna

We're currently using an internal fork that includes #37

We are using this to propagate down a unique Query ID from our SQL Builder.

Is there an alternative idea for accomplishing this outcome? Context on the span works well for us but feels bad to be using a closed PR.

Example code:

type ctxKeyQueryName struct{}

var queryNameKey = ctxKeyQueryName{}

func WithQueryName(ctx context.Context, queryName string) context.Context {
	return context.WithValue(ctx, queryNameKey, queryName)
}

func QueryName(ctx context.Context) string {
	if name, ok := ctx.Value(queryNameKey).(string); ok {
		return name
	}
	return ""
}

const sqlOperationUnknown = "UNKNOWN"

// firstField is like strings.Fields(), but only gets the first value, eg strings.Fields()[0], but more efficient.
func firstField(input string) string {
	start := -1
	for i, char := range input {
		if unicode.IsSpace(char) {
			if start != -1 {
				// We've found the end of the first word
				return input[start:i]
			}
		} else if start == -1 {
			// We've found the start of the first word
			start = i
		}
	}
	// If we reach here, return the whole word if it exists, or empty string if input was empty/only spaces
	if start != -1 {
		return input[start:]
	}
	return ""
}

func querySpanNameFunc(ctx context.Context, stmt string) string {
	qn := QueryName(ctx)
	if qn != "" {
		return qn
	}

	qn = firstField(stmt)
	if qn != "" {
		return qn
	}
	return sqlOperationUnknown
}


func() biggerFunc() {
		tr := otelpgx.NewTracer(
			otelpgx.WithSpanNameFunc(querySpanNameFunc),
		)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions