MSP-8172 Add vendor
This commit is contained in:
1 parent
5175d87e08
commit
eb066cb055
2619 files changed
+757077
-2
No files matched your search
+124
@@ -0,0 +1,124 @@
|
||||
# Package `sentry`
|
||||
|
||||
Пакет `sentry` предоставляет интеграцию с Sentry SDK для централизованного сбора и отправки ошибок и событий, с возможностью обогащения контекста через `context.Context` и функции обогащения событий.
|
||||
|
||||
## Types
|
||||
|
||||
### Config
|
||||
|
||||
Конфигурация для sentry
|
||||
|
||||
**Fields:**
|
||||
|
||||
#### `Enable bool`
|
||||
|
||||
Флаг включения Sentry.
|
||||
|
||||
#### `Dsn string`
|
||||
|
||||
DSN Sentry.
|
||||
|
||||
#### `ModuleName string`
|
||||
|
||||
Имя сервиса/модуля.
|
||||
|
||||
#### `ModuleVersion string`
|
||||
|
||||
Версия модуля.
|
||||
|
||||
#### `Environment string`
|
||||
|
||||
Окружение (например, `prod`, `dev`).
|
||||
|
||||
#### `InstanceId string`
|
||||
|
||||
Уникальный ID инстанса.
|
||||
|
||||
#### `Tags map[string]string`
|
||||
|
||||
Дополнительные произвольные теги.
|
||||
|
||||
### Hub
|
||||
|
||||
Интерфейс `Hub` для отправки ошибок и событий.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `CatchError(ctx context.Context, err error, level log.Level)`
|
||||
|
||||
Отправить ошибку с уровнем логирования.
|
||||
|
||||
#### `CatchEvent(ctx context.Context, event *sentry.Event)`
|
||||
|
||||
Отправить события напрямую.
|
||||
|
||||
#### `Flush()`
|
||||
|
||||
Подождать отправки всех событий.
|
||||
|
||||
### EventEnrichment
|
||||
|
||||
Функция обогащения события — добавляет произвольные данные в `sentry.Event`.
|
||||
|
||||
## Logger
|
||||
|
||||
- Проксирует все методы логгера.
|
||||
- Автоматически отправляет события в Sentry, если уровень лога присутствует в `supportedLevels`.
|
||||
- Добавляет в событие:
|
||||
|
||||
- уровень логирования,
|
||||
- `requestId` из контекста (если есть),
|
||||
- ошибку (если передана в лог),
|
||||
- данные обогащения из контекста.
|
||||
|
||||
## Реализации Hub
|
||||
|
||||
### SdkHub
|
||||
|
||||
Реальная обёртка над `sentry.Hub`. Отправляет события в Sentry SDK.
|
||||
|
||||
### NoopHub
|
||||
|
||||
Заглушка, которая ничего не делает. Используется, если Sentry отключён.
|
||||
|
||||
## Functions
|
||||
|
||||
### `func NewHubFromConfiguration(config Config) (Hub, error)`
|
||||
|
||||
Создаёт `Hub` на основе конфигурации. Возвращает `NoopHub`, если `Enable == false`.
|
||||
|
||||
### `func EnrichEvent(ctx context.Context, enrichment EventEnrichment) context.Context`
|
||||
|
||||
Добавляет функцию обогащения события в контекст. Используется для динамического расширения `sentry.Event` в `Logger`.
|
||||
|
||||
### `func WrapLogger(logger log.Logger, hub Hub, supportedLevels []log.Level) Logger`
|
||||
|
||||
Оборачивает логгер, чтобы автоматически отправлять события в Sentry на указанных уровнях (`supportedLevels`).
|
||||
|
||||
### `func WrapErrorLogger(logger log.Logger, hub Hub) Logger`
|
||||
|
||||
Упрощённый вариант `WrapLogger`, логирует только ошибки (`log.LevelError`).
|
||||
|
||||
## Usage
|
||||
|
||||
### Оборачивание логгера
|
||||
|
||||
```go
|
||||
wrappedLogger := sentry.WrapLogger(baseLogger, hub, []log.Level{log.LevelError, log.LevelFatal})
|
||||
```
|
||||
|
||||
### Обогащение событий
|
||||
|
||||
```go
|
||||
ctx = sentry.EnrichEvent(ctx, func(event *sentry.Event) {
|
||||
event.Extra["user_id"] = 12345
|
||||
})
|
||||
```
|
||||
|
||||
### Использование с контекстом
|
||||
|
||||
```go
|
||||
hub.CatchError(ctx, err, log.LevelError)
|
||||
```
|
||||
|
||||
Ошибка будет автоматически дополнена `requestId` и пользовательскими полями из `EnrichEvent`.
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package sentry
|
||||
|
||||
// Config holds the configuration for Sentry integration.
|
||||
type Config struct {
|
||||
// Enable determines whether Sentry is enabled.
|
||||
Enable bool
|
||||
// Dsn is the Sentry Data Source Name. Required when Enable is true.
|
||||
Dsn string
|
||||
// ModuleName identifies the service or module sending events.
|
||||
ModuleName string
|
||||
// ModuleVersion is the version of the module.
|
||||
ModuleVersion string
|
||||
// Environment specifies the environment (e.g., "production", "development").
|
||||
Environment string
|
||||
// InstanceId uniquely identifies the running instance.
|
||||
InstanceId string
|
||||
// Tags are key-value pairs attached to all events.
|
||||
Tags map[string]string
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package sentry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
)
|
||||
|
||||
// contextEnrichmentKey is used as a context key for event enrichment functions.
|
||||
type contextEnrichmentKey struct{}
|
||||
|
||||
// contextKeyValue is the global context key for event enrichment.
|
||||
//
|
||||
//go:generate stringer -type=contextEnrichmentKey
|
||||
var (
|
||||
contextKeyValue = contextEnrichmentKey{}
|
||||
)
|
||||
|
||||
// EventEnrichment is a function type that modifies a Sentry event.
|
||||
// It can be used to add custom tags, context, or other metadata to events.
|
||||
type EventEnrichment func(event *sentry.Event)
|
||||
|
||||
// EnrichEvent adds an event enrichment function to the context.
|
||||
// The enrichment function will be called for all subsequent log events in this context.
|
||||
// This allows adding custom metadata to events based on runtime context.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// ctx := sentry.EnrichEvent(ctx, func(event *sentry.Event) {
|
||||
// event.Tags["user-id"] = userID
|
||||
// event.Tags["request-type"] = "api"
|
||||
// })
|
||||
func EnrichEvent(ctx context.Context, enrichment EventEnrichment) context.Context {
|
||||
return context.WithValue(ctx, contextKeyValue, enrichment)
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
// Package sentry provides integration with Sentry for error tracking and event monitoring.
|
||||
//
|
||||
// This package wraps the Sentry Go SDK to provide a simple interface for capturing errors
|
||||
// and events from your application. It includes support for log integration, event enrichment,
|
||||
// and graceful fallback when Sentry is disabled.
|
||||
//
|
||||
// # Basic Usage
|
||||
//
|
||||
// Create a hub from configuration:
|
||||
//
|
||||
// hub, err := sentry.NewHubFromConfiguration(sentry.Config{
|
||||
// Enable: true,
|
||||
// Dsn: "your-sentry-dsn",
|
||||
// ModuleName: "my-service",
|
||||
// ModuleVersion: "v1.0.0",
|
||||
// Environment: "production",
|
||||
// })
|
||||
//
|
||||
// Wrap a logger to automatically capture log events:
|
||||
//
|
||||
// logger := sentry.WrapErrorLogger(log.Default(), hub)
|
||||
// logger.Error(ctx, "something went wrong", log.String("key", "value"))
|
||||
//
|
||||
// # Event Enrichment
|
||||
//
|
||||
// You can enrich events with custom context using EnrichEvent:
|
||||
//
|
||||
// ctx := sentry.EnrichEvent(ctx, func(event *sentry.Event) {
|
||||
// event.Tags["custom-tag"] = "custom-value"
|
||||
// })
|
||||
package sentry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"maps"
|
||||
"time"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
)
|
||||
|
||||
const (
|
||||
// RequestIdKey is the key used to store the request ID in event extra data.
|
||||
RequestIdKey = "requestId"
|
||||
|
||||
// defaultTransportTimeout is the timeout for sending events to Sentry.
|
||||
defaultTransportTimeout = 3 * time.Second
|
||||
// defaultEventBufferSize is the buffer size for the Sentry transport.
|
||||
defaultEventBufferSize = 10
|
||||
)
|
||||
|
||||
// SdkHub is the concrete implementation of the Hub interface using the Sentry Go SDK.
|
||||
type SdkHub struct {
|
||||
hub *sentry.Hub
|
||||
}
|
||||
|
||||
// NewHubFromConfiguration creates a new Hub from the provided configuration.
|
||||
// If Enable is false, it returns a NoopHub that discards all events.
|
||||
// Returns an error if Dsn is empty when Enable is true.
|
||||
//
|
||||
// The created Hub is safe for concurrent use.
|
||||
func NewHubFromConfiguration(config Config) (Hub, error) {
|
||||
if !config.Enable {
|
||||
return NewNoopHub(), nil
|
||||
}
|
||||
|
||||
if config.Dsn == "" {
|
||||
return nil, errors.New("sentry is enabled. dsn must be specified. check sentry configuration")
|
||||
}
|
||||
|
||||
allTags := map[string]string{
|
||||
"version": config.ModuleVersion,
|
||||
}
|
||||
if config.InstanceId != "" {
|
||||
allTags["instanceId"] = config.InstanceId
|
||||
}
|
||||
|
||||
maps.Copy(allTags, config.Tags)
|
||||
|
||||
buffedTransport := sentry.NewHTTPTransport()
|
||||
buffedTransport.Timeout = defaultTransportTimeout
|
||||
buffedTransport.BufferSize = defaultEventBufferSize
|
||||
|
||||
client, err := sentry.NewClient(sentry.ClientOptions{
|
||||
Dsn: config.Dsn,
|
||||
Transport: buffedTransport,
|
||||
ServerName: config.ModuleName,
|
||||
Environment: config.Environment,
|
||||
Release: "undefined",
|
||||
Tags: allTags,
|
||||
Integrations: func(integrations []sentry.Integration) []sentry.Integration {
|
||||
filtered := make([]sentry.Integration, 0, len(integrations))
|
||||
ignoredIntegrations := map[string]bool{
|
||||
"Modules": true,
|
||||
"Environment": true,
|
||||
}
|
||||
for _, integration := range integrations {
|
||||
if ignoredIntegrations[integration.Name()] {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, integration)
|
||||
}
|
||||
return filtered
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create sdk client")
|
||||
}
|
||||
|
||||
hub := sentry.NewHub(client, sentry.NewScope())
|
||||
|
||||
return SdkHub{
|
||||
hub: hub,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CatchError captures an error with the specified log level.
|
||||
// It maps the log level to a Sentry level and extracts the error stack trace.
|
||||
// If a request ID is present in the context, it is added to the event.
|
||||
func (s SdkHub) CatchError(ctx context.Context, err error, level log.Level) {
|
||||
eventLevel := sentry.LevelError
|
||||
levelFromMapping, ok := logLevelMapping[level]
|
||||
if ok {
|
||||
eventLevel = levelFromMapping
|
||||
}
|
||||
event := &sentry.Event{
|
||||
Level: eventLevel,
|
||||
Message: err.Error(),
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
SetException(event, err)
|
||||
|
||||
requestId := requestid.FromContext(ctx)
|
||||
if requestId != "" {
|
||||
event.Tags = map[string]string{
|
||||
RequestIdKey: requestId,
|
||||
}
|
||||
}
|
||||
|
||||
s.CatchEvent(ctx, event)
|
||||
}
|
||||
|
||||
// CatchEvent captures a Sentry event directly.
|
||||
// The event is sent asynchronously to Sentry.
|
||||
func (s SdkHub) CatchEvent(ctx context.Context, event *sentry.Event) {
|
||||
s.hub.CaptureEvent(event)
|
||||
}
|
||||
|
||||
// Flush waits for all buffered events to be sent to Sentry.
|
||||
// It blocks until the transport timeout or until all events are sent.
|
||||
func (s SdkHub) Flush() {
|
||||
s.hub.Flush(defaultTransportTimeout)
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package sentry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// Hub defines the interface for Sentry operations.
|
||||
// It provides methods for capturing errors and events, and flushing pending events.
|
||||
type Hub interface {
|
||||
// CatchError captures an error with the specified log level.
|
||||
// The error is extracted from the context and sent to Sentry.
|
||||
CatchError(ctx context.Context, err error, level log.Level)
|
||||
// CatchEvent captures a Sentry event directly.
|
||||
CatchEvent(ctx context.Context, event *sentry.Event)
|
||||
// Flush waits for any buffered events to be sent to Sentry.
|
||||
Flush()
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package sentry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// logLevelMapping maps log levels to Sentry event levels.
|
||||
var (
|
||||
logLevelMapping = map[log.Level]sentry.Level{
|
||||
log.FatalLevel: sentry.LevelFatal,
|
||||
log.ErrorLevel: sentry.LevelError,
|
||||
log.WarnLevel: sentry.LevelWarning,
|
||||
log.InfoLevel: sentry.LevelInfo,
|
||||
log.DebugLevel: sentry.LevelDebug,
|
||||
}
|
||||
)
|
||||
|
||||
// Logger wraps a log.Logger and forwards log events to Sentry.
|
||||
// It provides structured logging with automatic error capture and context enrichment.
|
||||
type Logger struct {
|
||||
delegate log.Logger
|
||||
hub Hub
|
||||
supportedLevels map[log.Level]sentry.Level
|
||||
}
|
||||
|
||||
// WrapErrorLogger creates a Logger that captures only error-level events.
|
||||
// It delegates all logging to the underlying logger and sends errors to Sentry.
|
||||
func WrapErrorLogger(logger log.Logger, hub Hub) Logger {
|
||||
return WrapLogger(
|
||||
logger,
|
||||
hub,
|
||||
[]log.Level{log.ErrorLevel},
|
||||
)
|
||||
}
|
||||
|
||||
// WrapLogger creates a Logger that captures events at the specified log levels.
|
||||
// Only the levels in supportedLevels will be forwarded to Sentry.
|
||||
// The returned Logger is safe for concurrent use.
|
||||
func WrapLogger(logger log.Logger, hub Hub, supportedLevels []log.Level) Logger {
|
||||
levels := make(map[log.Level]sentry.Level)
|
||||
for _, level := range supportedLevels {
|
||||
levels[level] = logLevelMapping[level]
|
||||
}
|
||||
|
||||
return Logger{
|
||||
delegate: logger,
|
||||
hub: hub,
|
||||
supportedLevels: levels,
|
||||
}
|
||||
}
|
||||
|
||||
// Error logs an error message and forwards it to Sentry if ErrorLevel is supported.
|
||||
// It delegates to the underlying logger and captures the error with full context.
|
||||
func (s Logger) Error(ctx context.Context, message any, fields ...log.Field) {
|
||||
s.delegate.Error(ctx, message, fields...)
|
||||
s.log(log.ErrorLevel, ctx, message, fields...)
|
||||
}
|
||||
|
||||
// Warn logs a warning message and forwards it to Sentry if WarnLevel is supported.
|
||||
func (s Logger) Warn(ctx context.Context, message any, fields ...log.Field) {
|
||||
s.delegate.Warn(ctx, message, fields...)
|
||||
s.log(log.WarnLevel, ctx, message, fields...)
|
||||
}
|
||||
|
||||
// Info logs an informational message and forwards it to Sentry if InfoLevel is supported.
|
||||
func (s Logger) Info(ctx context.Context, message any, fields ...log.Field) {
|
||||
s.delegate.Info(ctx, message, fields...)
|
||||
s.log(log.InfoLevel, ctx, message, fields...)
|
||||
}
|
||||
|
||||
// Debug logs a debug message and forwards it to Sentry if DebugLevel is supported.
|
||||
func (s Logger) Debug(ctx context.Context, message any, fields ...log.Field) {
|
||||
s.delegate.Debug(ctx, message, fields...)
|
||||
s.log(log.DebugLevel, ctx, message, fields...)
|
||||
}
|
||||
|
||||
// log forwards a log event to Sentry if the level is supported and the hub is not a NoopHub.
|
||||
// It extracts error information from fields and enriches the event with context.
|
||||
func (s Logger) log(level log.Level, ctx context.Context, message any, fields ...log.Field) {
|
||||
sentryLevel, isSupported := s.supportedLevels[level]
|
||||
if !isSupported {
|
||||
return
|
||||
}
|
||||
|
||||
_, isNoopHub := s.hub.(NoopHub)
|
||||
if isNoopHub {
|
||||
return
|
||||
}
|
||||
|
||||
event := EventFromLog(sentryLevel, ctx, message, fields...)
|
||||
s.hub.CatchEvent(ctx, event)
|
||||
}
|
||||
|
||||
// EventFromLog creates a Sentry event from a log entry.
|
||||
// It extracts the error from the message or fields, enriches the event with context values,
|
||||
// and applies any event enrichment functions from the context.
|
||||
// The returned event includes the request ID if present in the context.
|
||||
func EventFromLog(
|
||||
level sentry.Level,
|
||||
ctx context.Context,
|
||||
message any,
|
||||
fields ...log.Field,
|
||||
) *sentry.Event {
|
||||
errInLog, _ := message.(error)
|
||||
|
||||
tags := make(map[string]string, len(fields))
|
||||
for _, field := range log.ContextLogValues(ctx) {
|
||||
value := fieldToString(field)
|
||||
tags[field.Key] = value
|
||||
}
|
||||
for _, field := range fields {
|
||||
value := fieldToString(field)
|
||||
tags[field.Key] = value
|
||||
errField := errorFromField(field)
|
||||
if errInLog == nil {
|
||||
errInLog = errField
|
||||
}
|
||||
}
|
||||
|
||||
requestId := requestid.FromContext(ctx)
|
||||
if requestId != "" {
|
||||
tags["requestId"] = requestId
|
||||
}
|
||||
|
||||
event := &sentry.Event{
|
||||
Tags: tags,
|
||||
Level: level,
|
||||
Message: fmt.Sprintf("%v", message),
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
if errInLog != nil {
|
||||
SetException(event, errInLog)
|
||||
}
|
||||
|
||||
enrichment, ok := ctx.Value(contextKeyValue).(EventEnrichment)
|
||||
if ok {
|
||||
enrichment(event)
|
||||
}
|
||||
|
||||
return event
|
||||
}
|
||||
|
||||
// SetException extracts the error chain from an error and sets it on the Sentry event.
|
||||
// Unlike the Sentry SDK's SetException, it only includes stack traces where they exist.
|
||||
// The exception list is reversed to show the root cause first.
|
||||
func SetException(e *sentry.Event, exception error) {
|
||||
err := exception
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
for i := 0; i < 10 && err != nil; i++ {
|
||||
e.Exception = append(e.Exception, sentry.Exception{
|
||||
Value: err.Error(),
|
||||
Type: reflect.TypeOf(err).String(),
|
||||
Stacktrace: sentry.ExtractStacktrace(err),
|
||||
})
|
||||
// nolint:errorlint
|
||||
switch previous := err.(type) {
|
||||
case interface{ Unwrap() error }:
|
||||
err = previous.Unwrap()
|
||||
case interface{ Cause() error }:
|
||||
err = previous.Cause()
|
||||
default:
|
||||
err = nil
|
||||
}
|
||||
}
|
||||
|
||||
slices.Reverse(e.Exception)
|
||||
}
|
||||
|
||||
// nolint:forcetypeassert
|
||||
// fieldToString converts a log.Field to a Go string.
|
||||
// It handles various field types including strings, booleans, times, durations, and stringers.
|
||||
func fieldToString(field log.Field) string {
|
||||
switch {
|
||||
case field.String != "":
|
||||
return field.String
|
||||
case field.Type == zapcore.BoolType:
|
||||
return fmt.Sprintf("%v", field.Integer == 1)
|
||||
case field.Type == zapcore.ByteStringType:
|
||||
return string(field.Interface.([]byte))
|
||||
case field.Type == zapcore.StringerType:
|
||||
return field.Interface.(fmt.Stringer).String()
|
||||
case field.Type == zapcore.DurationType:
|
||||
return time.Duration(field.Integer).String()
|
||||
case field.Type == zapcore.TimeType:
|
||||
return time.Unix(0, field.Integer).In(field.Interface.(*time.Location)).Format("2006-01-02T15:04:05.000Z0700")
|
||||
case field.Interface != nil:
|
||||
return fmt.Sprintf("%v", field.Interface)
|
||||
default:
|
||||
return fmt.Sprintf("%v", field.Integer)
|
||||
}
|
||||
}
|
||||
|
||||
// errorFromField extracts an error from a log.Field if it is an error type.
|
||||
// Returns nil if the field is not an error.
|
||||
func errorFromField(field log.Field) error {
|
||||
if field.Type == zapcore.ErrorType {
|
||||
return field.Interface.(error) // nolint:forcetypeassert
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package sentry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// NoopHub is a no-operation implementation of the Hub interface.
|
||||
// It discards all events and errors without sending them to Sentry.
|
||||
// Use this when Sentry is disabled to avoid nil pointer issues.
|
||||
// The NoopHub is safe for concurrent use.
|
||||
type NoopHub struct {
|
||||
}
|
||||
|
||||
// NewNoopHub creates a new NoopHub instance.
|
||||
func NewNoopHub() NoopHub {
|
||||
return NoopHub{}
|
||||
}
|
||||
|
||||
// CatchError discards the error without any action.
|
||||
func (n NoopHub) CatchError(ctx context.Context, err error, level log.Level) {
|
||||
}
|
||||
|
||||
// CatchEvent discards the event without any action.
|
||||
func (n NoopHub) CatchEvent(ctx context.Context, event *sentry.Event) {
|
||||
|
||||
}
|
||||
|
||||
// Flush performs no action.
|
||||
func (n NoopHub) Flush() {
|
||||
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
# Package `tracing`
|
||||
|
||||
Пакет `tracing` предоставляет интерфейсы и реализацию для инициализации трассировки с помощью OpenTelemetry, включая поддержку `OTLP` экспортёра, `TracerProvider`, `Propagator`, а также noop-реализацию.
|
||||
|
||||
## Types
|
||||
|
||||
### Config
|
||||
|
||||
Конфигурация для инициализации трассировки:
|
||||
|
||||
**Fields:**
|
||||
|
||||
#### `Enable bool`
|
||||
|
||||
Включает или отключает трассировку.
|
||||
|
||||
#### `Address string`
|
||||
|
||||
Адрес OTLP-экспортера (например, `localhost:4318`).
|
||||
|
||||
#### `ModuleName string`
|
||||
|
||||
Название сервиса.
|
||||
|
||||
#### `ModuleVersion string`
|
||||
|
||||
Версия сервиса
|
||||
|
||||
#### `Environment string`
|
||||
|
||||
Окружение выполнения (например, `prod`, `staging`).
|
||||
|
||||
#### `InstanceId string`
|
||||
|
||||
Уникальный идентификатор инстанса.
|
||||
|
||||
#### `Attributes map[string]string`
|
||||
|
||||
Дополнительные атрибуты, которые будут прикреплены к каждому спану.
|
||||
|
||||
### TracerProvider
|
||||
|
||||
Псевдоним для стандартного интерфейса OpenTelemetry `TracerProvider`.
|
||||
|
||||
### Propagator
|
||||
|
||||
Псевдоним для интерфейса `TextMapPropagator`, используемого для распространения контекста трассировки между сервисами.
|
||||
|
||||
### Provider
|
||||
|
||||
Интерфейс трассировщика, поддерживающий корректное завершение сессии через `Shutdown()`.
|
||||
|
||||
**Methods:**
|
||||
#### `func NewProviderFromConfiguration(ctx context.Context, logger log.Logger, config Config) (Provider, error)`
|
||||
|
||||
Создаёт и возвращает `TracerProvider` на основе переданной конфигурации. Возвращает `NoopProvider`, если `Enable == false`.
|
||||
|
||||
Использует OTLP экспортёр через HTTP и устанавливает атрибуты ресурса:
|
||||
|
||||
- окружение,
|
||||
- имя сервиса,
|
||||
- версия,
|
||||
- идентификатор инстанса,
|
||||
- пользовательские атрибуты.
|
||||
|
||||
## Constants
|
||||
|
||||
```go
|
||||
const RequestId = attribute.Key("app.request_id")
|
||||
```
|
||||
|
||||
Ключ атрибута, используемый для добавления request-id в спан. Применяется как часть метаданных запроса.
|
||||
|
||||
## Global variables
|
||||
|
||||
```go
|
||||
var (
|
||||
DefaultPropagator Propagator = propagation.TraceContext{}
|
||||
DefaultProvider TracerProvider = NewNoopProvider()
|
||||
)
|
||||
```
|
||||
|
||||
Значения по умолчанию:
|
||||
|
||||
- `DefaultPropagator` — TraceContext propagator.
|
||||
- `DefaultProvider` — noop-реализация трассировщика.
|
||||
|
||||
## NoopProvider
|
||||
|
||||
Реализация `TracerProvider`, которая не делает ничего (используется по умолчанию при отключенной трассировке).
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `func NewNoopProvider() NoopProvider`
|
||||
|
||||
Создаёт новый `NoopProvider`.
|
||||
|
||||
#### `(n NoopProvider) Tracer(name string, options ...trace.TracerOption) trace.Tracer`
|
||||
|
||||
Возвращает пустой `noop.Tracer`.
|
||||
|
||||
#### `(n NoopProvider) Shutdown(ctx context.Context) error`
|
||||
|
||||
Операция завершения, не выполняющая действий.
|
||||
|
||||
#### `func IsNoop(provider TracerProvider) bool`
|
||||
|
||||
Проверяет, является ли провайдер noop-реализацией.
|
||||
|
||||
## Usage
|
||||
|
||||
Пример настройки трассировки с использованием OTLP экспортёра и установкой глобального провайдера.
|
||||
Завершение трассировки выполняется через `Shutdown`.
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
...
|
||||
"github.com/txix-open/observability/tracing"
|
||||
"go.opentelemetry.io/otel"
|
||||
...
|
||||
)
|
||||
|
||||
func main(){
|
||||
...
|
||||
cfg := tracing.Config{
|
||||
Enable: true,
|
||||
Address: "localhost:4318",
|
||||
ModuleName: "user-service",
|
||||
ModuleVersion: "1.0.0",
|
||||
Environment: "production",
|
||||
InstanceId: "abc123",
|
||||
Attributes: map[string]string{
|
||||
"region": "eu-central-1",
|
||||
},
|
||||
}
|
||||
|
||||
provider, err := tracing.NewProviderFromConfiguration(context.Background(), logger, cfg)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
otel.SetTracerProvider(provider)
|
||||
defer provider.Shutdown(context.Background())
|
||||
...
|
||||
}
|
||||
```
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package tracing
|
||||
|
||||
// Config holds the configuration for the tracing provider.
|
||||
type Config struct {
|
||||
// Enable determines whether tracing is enabled.
|
||||
Enable bool
|
||||
// Address specifies the OTLP collector endpoint address.
|
||||
Address string
|
||||
// ModuleName identifies the service name.
|
||||
ModuleName string
|
||||
// ModuleVersion specifies the service version.
|
||||
ModuleVersion string
|
||||
// Environment defines the deployment environment.
|
||||
Environment string
|
||||
// InstanceId uniquely identifies the service instance.
|
||||
InstanceId string
|
||||
// Attributes contains additional custom attributes for the resource.
|
||||
Attributes map[string]string
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
// Package grpc provides utilities for gRPC tracing integration.
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
// MetadataCarrier implements the TextMapCarrier interface for gRPC metadata.
|
||||
type MetadataCarrier metadata.MD
|
||||
|
||||
// Get returns the first value associated with the given key.
|
||||
func (m MetadataCarrier) Get(key string) string {
|
||||
value := metadata.MD(m).Get(key)
|
||||
if len(value) == 0 {
|
||||
return ""
|
||||
}
|
||||
return value[0]
|
||||
}
|
||||
|
||||
// Set associates a key-value pair in the metadata.
|
||||
func (m MetadataCarrier) Set(key string, value string) {
|
||||
metadata.MD(m).Set(key, value)
|
||||
}
|
||||
|
||||
// Keys returns all keys in the metadata.
|
||||
func (m MetadataCarrier) Keys() []string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for key := range m {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
Generated
Vendored
+62
@@ -0,0 +1,62 @@
|
||||
# Package `client_tracing`
|
||||
|
||||
Пакет `client_tracing` предназначен для добавления middleware к gRPC-клиенту с поддержкой распределённой трассировки через OpenTelemetry. Позволяет автоматически создавать и передавать span-контекст при выполнении gRPC-запросов, а также записывать статусы и ошибки вызовов в трассировку.
|
||||
|
||||
## Types
|
||||
|
||||
### Config
|
||||
|
||||
Структура `Config` представляет конфигурацию трассировки для gRPC-клиента.
|
||||
|
||||
**Fields:**
|
||||
|
||||
#### `Provider`
|
||||
|
||||
Реализация интерфейса `tracing.TracerProvider`, используемая для создания спанов.
|
||||
|
||||
#### `Propagator`
|
||||
|
||||
Реализация интерфейса `tracing.Propagator`, используемая для инъекции и извлечения контекста трассировки.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `func NewConfig() Config`
|
||||
|
||||
Создаёт конфигурацию трассировки с `provider` и `propagator` по умолчанию.
|
||||
|
||||
#### `func (c Config) Middleware() request.Middleware`
|
||||
|
||||
Возвращает middleware для клиента gRPC, реализующего трассировку запроса. Если трассировка отключена (noop-провайдер), возвращается middleware-заглушка.
|
||||
|
||||
Middleware:
|
||||
|
||||
- Создаёт новый спан для каждого gRPC-вызова с именем `GRPC call <endpoint>`.
|
||||
- Устанавливает `span kind` в значение `Client`.
|
||||
- Добавляет `request_id` в атрибуты спана.
|
||||
- Инъецирует контекст в metadata запроса.
|
||||
- В случае ошибки записывает её в спан и устанавливает статус `Error`.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing"
|
||||
)
|
||||
func main() {
|
||||
...
|
||||
cfg := client_tracing.NewConfig()
|
||||
client := client.New(
|
||||
client.WithMiddleware(
|
||||
cfg.Middleware(),
|
||||
),
|
||||
)
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Для корректной работы необходимо, чтобы в контексте присутствовал `request_id`, а также был корректно настроен глобальный TracerProvider и Propagator OpenTelemetry.
|
||||
Generated
Vendored
+77
@@ -0,0 +1,77 @@
|
||||
// Package client_tracing provides gRPC client middleware for distributed tracing.
|
||||
package client_tracing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/observability/tracing"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/grpc"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// tracerName identifies the tracer for gRPC client tracing.
|
||||
const tracerName = "isp-kit/observability/tracing/grpc"
|
||||
|
||||
// Config holds the configuration for the gRPC client tracing middleware.
|
||||
type Config struct {
|
||||
// Provider is the tracer provider used to create tracers.
|
||||
Provider tracing.TracerProvider
|
||||
// Propagator is the text map propagator for context propagation.
|
||||
Propagator tracing.Propagator
|
||||
}
|
||||
|
||||
// NewConfig creates a new Config with default values.
|
||||
func NewConfig() Config {
|
||||
return Config{
|
||||
Provider: tracing.DefaultProvider,
|
||||
Propagator: tracing.DefaultPropagator,
|
||||
}
|
||||
}
|
||||
|
||||
// Middleware returns a gRPC client middleware that creates spans for outgoing RPC calls.
|
||||
// It injects trace context into the request metadata, creates a client span, and records
|
||||
// errors. If the provider is a no-op, it returns a pass-through middleware.
|
||||
func (c Config) Middleware() request.Middleware {
|
||||
if tracing.IsNoop(c.Provider) {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
return next(ctx, builder, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracer := c.Provider.Tracer(tracerName)
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
attributes := []attribute.KeyValue{
|
||||
tracing.RequestId.String(requestid.FromContext(ctx)),
|
||||
}
|
||||
opts := []trace.SpanStartOption{
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(attributes...),
|
||||
}
|
||||
|
||||
clientEndpoint := builder.Endpoint
|
||||
spanName := fmt.Sprintf("GRPC call %s", clientEndpoint)
|
||||
|
||||
ctx, span := tracer.Start(ctx, spanName, opts...)
|
||||
defer span.End()
|
||||
|
||||
c.Propagator.Inject(ctx, grpc.MetadataCarrier(builder.MD))
|
||||
|
||||
resp, err := next(ctx, builder, message)
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
}
|
||||
|
||||
return resp, err
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+95
@@ -0,0 +1,95 @@
|
||||
# Package `server_tracing`
|
||||
|
||||
Пакет `server_tracing` предоставляет middleware для серверов gRPC, реализующих трассировку входящих запросов с использованием OpenTelemetry.
|
||||
|
||||
## Types
|
||||
|
||||
### Config
|
||||
|
||||
Структура `Config` предназначена для конфигурации middleware трассировки gRPC-сервера. Она содержит провайдер трассировки и пропагатор контекста.
|
||||
|
||||
**Fields:**
|
||||
|
||||
#### `Provider tracing.TracerProvider`
|
||||
|
||||
Реализация интерфейса `tracing.TracerProvider`, используемая для создания спанов.
|
||||
|
||||
#### `Propagator tracing.Propagator`
|
||||
|
||||
Реализация интерфейса `tracing.Propagator`, используемая для инъекции и извлечения контекста трассировки.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `func NewConfig() Config`
|
||||
|
||||
Создаёт конфигурацию трассировки с `provider` и `propagator` по умолчанию.
|
||||
|
||||
#### `func (c Config) Middleware() grpc.Middleware`
|
||||
|
||||
Создаёт middleware для трассировки gRPC-запросов. Возвращаемый middleware:
|
||||
|
||||
- Извлекает контекст трассировки из входящих метаданных;
|
||||
- Инициирует span с именем, основанным на методе gRPC-запроса (если доступно);
|
||||
- Добавляет атрибут `request.id`;
|
||||
- Фиксирует ошибку в span, если она произошла;
|
||||
- Завершает span после выполнения запроса.
|
||||
|
||||
Если трассировка отключена (noop-провайдер), возвращается no-op middleware.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
|
||||
"github.com/txix-open/isp-kit/validator"
|
||||
|
||||
"github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing"
|
||||
)
|
||||
|
||||
func main(){
|
||||
...
|
||||
|
||||
tracingCfg := server_tracing.NewConfig()
|
||||
server := grpc.DefaultServer()
|
||||
|
||||
logger, _ := log.New()
|
||||
paramMappers := []endpoint.ParamMapper{
|
||||
ContextParam(),
|
||||
AuthDataParam(),
|
||||
}
|
||||
middlewares := append(
|
||||
[]grpc.Middleware{
|
||||
RequestId(),
|
||||
server_tracing.NewConfig().Middleware(),
|
||||
ErrorHandler(logger),
|
||||
Recovery(),
|
||||
},
|
||||
restMiddlewares...,
|
||||
)
|
||||
wrapper := NewWrapper(
|
||||
paramMappers,
|
||||
JsonRequestExtractor{Validator: validator.Default},
|
||||
JsonResponseMapper{},
|
||||
).WithMiddlewares(middlewares...)
|
||||
|
||||
mux := grpc.NewMux()
|
||||
mux.Handle("some_endpoint", wrapper.Endpoint(func(ctx context.Context) error {
|
||||
// реализация
|
||||
return nil
|
||||
}))
|
||||
|
||||
server.Upgrade(mux)
|
||||
|
||||
server.ListenAndServe(":8080")
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+87
@@ -0,0 +1,87 @@
|
||||
// Package server_tracing provides gRPC server middleware for distributed tracing.
|
||||
package server_tracing
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/log/logutil"
|
||||
"github.com/txix-open/isp-kit/observability/tracing"
|
||||
grpc2 "github.com/txix-open/isp-kit/observability/tracing/grpc"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
// tracerName identifies the tracer for gRPC server tracing.
|
||||
const tracerName = "isp-kit/observability/tracing/grpc"
|
||||
|
||||
// Config holds the configuration for the gRPC server tracing middleware.
|
||||
type Config struct {
|
||||
// Provider is the tracer provider used to create tracers.
|
||||
Provider tracing.TracerProvider
|
||||
// Propagator is the text map propagator for context propagation.
|
||||
Propagator tracing.Propagator
|
||||
}
|
||||
|
||||
// NewConfig creates a new Config with default values.
|
||||
func NewConfig() Config {
|
||||
return Config{
|
||||
Provider: tracing.DefaultProvider,
|
||||
Propagator: tracing.DefaultPropagator,
|
||||
}
|
||||
}
|
||||
|
||||
// Middleware returns a gRPC server middleware that creates spans for incoming RPC calls.
|
||||
// It extracts trace context from request metadata, creates a server span, and records
|
||||
// errors at the appropriate log level. If the provider is a no-op, it returns a pass-through middleware.
|
||||
func (c Config) Middleware() grpc.Middleware {
|
||||
if tracing.IsNoop(c.Provider) {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
return next(ctx, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracer := c.Provider.Tracer(tracerName)
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
if md == nil {
|
||||
md = metadata.MD{}
|
||||
}
|
||||
spanName, _ := grpc.StringFromMd(grpc.ProxyMethodNameHeader, md)
|
||||
if spanName == "" {
|
||||
return next(ctx, message)
|
||||
}
|
||||
|
||||
ctx = c.Propagator.Extract(ctx, grpc2.MetadataCarrier(md))
|
||||
|
||||
attributes := []attribute.KeyValue{
|
||||
tracing.RequestId.String(requestid.FromContext(ctx)),
|
||||
}
|
||||
opts := []trace.SpanStartOption{
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(attributes...),
|
||||
}
|
||||
|
||||
ctx, span := tracer.Start(ctx, spanName, opts...)
|
||||
defer span.End()
|
||||
|
||||
resp, err := next(ctx, message)
|
||||
|
||||
if err != nil {
|
||||
logLevel := logutil.LogLevelForError(err)
|
||||
if logLevel == log.ErrorLevel {
|
||||
span.RecordError(err)
|
||||
}
|
||||
}
|
||||
|
||||
return resp, err
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+64
@@ -0,0 +1,64 @@
|
||||
# Package `client_tracing`
|
||||
|
||||
Пакет `client_tracing` предоставляет middleware для трассировки исходящих HTTP-запросов с использованием OpenTelemetry.
|
||||
Он интегрируется с клиентом `httpcli` из `isp-kit` и добавляет в запросы span'ы и trace-информацию, в том числе request id и HTTP-атрибуты.
|
||||
|
||||
## Types
|
||||
|
||||
### Config
|
||||
|
||||
Структура `Config` определяет настройки трассировки для исходящих HTTP-запросов.
|
||||
|
||||
**Fields:**
|
||||
|
||||
#### `Provider tracing.TracerProvider`
|
||||
|
||||
Провайдер трассировки (по умолчанию `tracing.DefaultProvider`).
|
||||
|
||||
#### `Propagator tracing.Propagator`
|
||||
|
||||
Пропагатор контекста (по умолчанию `tracing.DefaultPropagator`).
|
||||
|
||||
#### `EnableHttpTracing bool`
|
||||
|
||||
Включает детализацию трейсинга через `net/http/httptrace`.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `func NewConfig() Config`
|
||||
|
||||
Создаёт конфигурацию трассировки с `provider` и `propagator` по умолчанию.
|
||||
|
||||
#### `(c Config) Middleware() httpcli.Middleware`
|
||||
|
||||
Создаёт middleware, оборачивающее `httpcli.RoundTripper` для добавления трейсинга в каждый HTTP-запрос.
|
||||
Выполняются следующие действия:
|
||||
|
||||
- Запуск нового спана с именем по шаблону `HTTP call METHOD URL_PATH`.
|
||||
- Добавление стандартных HTTP-атрибутов в span (метод, URL, статус-код и т.п.).
|
||||
- Инжекция trace-контекста в заголовки запроса.
|
||||
- В случае ошибки или получения ответа — установка соответствующего статуса в span.
|
||||
- При включённом `EnableHttpTracing` — подключение дополнительных `httptrace` хуков.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/http/client_tracing"
|
||||
)
|
||||
|
||||
func main(){
|
||||
...
|
||||
client := httpcli.New(
|
||||
httpcli.WithMiddleware(
|
||||
client_tracing.NewConfig().Middleware(),
|
||||
),
|
||||
)
|
||||
...
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+93
@@ -0,0 +1,93 @@
|
||||
// Package client_tracing provides HTTP client middleware for distributed tracing.
|
||||
package client_tracing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http/httptrace"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||
"github.com/txix-open/isp-kit/observability/tracing"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/http/semconvutil"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
"go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// tracerName identifies the tracer for HTTP client tracing.
|
||||
const tracerName = "isp-kit/observability/tracing/http"
|
||||
|
||||
// Config holds the configuration for the HTTP client tracing middleware.
|
||||
type Config struct {
|
||||
// Provider is the tracer provider used to create tracers.
|
||||
Provider tracing.TracerProvider
|
||||
// Propagator is the text map propagator for context propagation.
|
||||
Propagator tracing.Propagator
|
||||
// EnableHttpTracing enables detailed HTTP client tracing using otelhttptrace.
|
||||
EnableHttpTracing bool
|
||||
}
|
||||
|
||||
// NewConfig creates a new Config with default values.
|
||||
func NewConfig() Config {
|
||||
return Config{
|
||||
Provider: tracing.DefaultProvider,
|
||||
Propagator: tracing.DefaultPropagator,
|
||||
}
|
||||
}
|
||||
|
||||
// Middleware returns an HTTP client middleware that creates spans for outgoing requests.
|
||||
// It injects trace context into request headers, creates a client span, and records
|
||||
// response status and errors. If the provider is a no-op, it returns a pass-through middleware.
|
||||
func (c Config) Middleware() httpcli.Middleware {
|
||||
if tracing.IsNoop(c.Provider) {
|
||||
return func(next httpcli.RoundTripper) httpcli.RoundTripper {
|
||||
return httpcli.RoundTripperFunc(func(ctx context.Context, request *httpcli.Request) (*httpcli.Response, error) {
|
||||
return next.RoundTrip(ctx, request)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
tracer := c.Provider.Tracer(tracerName)
|
||||
return func(next httpcli.RoundTripper) httpcli.RoundTripper {
|
||||
return httpcli.RoundTripperFunc(func(ctx context.Context, request *httpcli.Request) (*httpcli.Response, error) {
|
||||
attributes := semconvutil.HTTPClientRequest(request.Raw)
|
||||
attributes = append(attributes, tracing.RequestId.String(requestid.FromContext(ctx)))
|
||||
opts := []trace.SpanStartOption{
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
}
|
||||
|
||||
clientEndpoint := http_metrics.ClientEndpoint(ctx)
|
||||
if clientEndpoint == "" {
|
||||
clientEndpoint = request.Raw.URL.Path
|
||||
}
|
||||
spanName := fmt.Sprintf("HTTP call %s %s", request.Raw.Method, clientEndpoint)
|
||||
|
||||
ctx, span := tracer.Start(ctx, spanName, opts...)
|
||||
defer span.End()
|
||||
|
||||
if c.EnableHttpTracing {
|
||||
otelHttpClientTrace := otelhttptrace.NewClientTrace(ctx, otelhttptrace.WithoutHeaders())
|
||||
ctx = httptrace.WithClientTrace(ctx, otelHttpClientTrace)
|
||||
}
|
||||
|
||||
c.Propagator.Inject(ctx, propagation.HeaderCarrier(request.Raw.Header))
|
||||
|
||||
resp, err := next.RoundTrip(ctx, request)
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
}
|
||||
if resp != nil && resp.Raw != nil {
|
||||
attributes = append(attributes, semconvutil.HTTPClientResponse(resp.Raw)...)
|
||||
span.SetStatus(semconvutil.HTTPClientStatus(resp.StatusCode()))
|
||||
}
|
||||
|
||||
span.SetAttributes(attributes...)
|
||||
|
||||
return resp, err
|
||||
})
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package semconvutil // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil"
|
||||
|
||||
// Generate semconvutil package:
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/semconvutil/httpconv_test.go.tmpl "--data={}" --out=httpconv_test.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/semconvutil/httpconv.go.tmpl "--data={}" --out=httpconv.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/semconvutil/netconv_test.go.tmpl "--data={}" --out=netconv_test.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/semconvutil/netconv.go.tmpl "--data={}" --out=netconv.go
|
||||
Generated
Vendored
+552
@@ -0,0 +1,552 @@
|
||||
// Code created by gotmpl. DO NOT MODIFY.
|
||||
// source: internal/shared/semconvutil/httpconv.go.tmpl
|
||||
|
||||
// Copyright The OpenTelemetry Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package semconvutil // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
|
||||
)
|
||||
|
||||
// HTTPClientResponse returns trace attributes for an HTTP response received by a
|
||||
// client from a server. It will return the following attributes if the related
|
||||
// values are defined in resp: "http.status.code",
|
||||
// "http.response_content_length".
|
||||
//
|
||||
// This does not add all OpenTelemetry required attributes for an HTTP event,
|
||||
// it assumes ClientRequest was used to create the span with a complete set of
|
||||
// attributes. If a complete set of attributes can be generated using the
|
||||
// request contained in resp. For example:
|
||||
//
|
||||
// append(HTTPClientResponse(resp), ClientRequest(resp.Request)...)
|
||||
func HTTPClientResponse(resp *http.Response) []attribute.KeyValue {
|
||||
return hc.ClientResponse(resp)
|
||||
}
|
||||
|
||||
// HTTPClientRequest returns trace attributes for an HTTP request made by a client.
|
||||
// The following attributes are always returned: "http.url", "http.flavor",
|
||||
// "http.method", "net.peer.name". The following attributes are returned if the
|
||||
// related values are defined in req: "net.peer.port", "http.user_agent",
|
||||
// "http.request_content_length", "enduser.id".
|
||||
func HTTPClientRequest(req *http.Request) []attribute.KeyValue {
|
||||
return hc.ClientRequest(req)
|
||||
}
|
||||
|
||||
// HTTPClientStatus returns a span status code and message for an HTTP status code
|
||||
// value received by a client.
|
||||
func HTTPClientStatus(code int) (codes.Code, string) {
|
||||
return hc.ClientStatus(code)
|
||||
}
|
||||
|
||||
// HTTPServerRequest returns trace attributes for an HTTP request received by a
|
||||
// server.
|
||||
//
|
||||
// The server must be the primary server name if it is known. For example this
|
||||
// would be the ServerName directive
|
||||
// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache
|
||||
// server, and the server_name directive
|
||||
// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an
|
||||
// nginx server. More generically, the primary server name would be the host
|
||||
// header value that matches the default virtual host of an HTTP server. It
|
||||
// should include the host identifier and if a port is used to route to the
|
||||
// server that port identifier should be included as an appropriate port
|
||||
// suffix.
|
||||
//
|
||||
// If the primary server name is not known, server should be an empty string.
|
||||
// The req Host will be used to determine the server instead.
|
||||
//
|
||||
// The following attributes are always returned: "http.method", "http.scheme",
|
||||
// "http.flavor", "http.target", "net.host.name". The following attributes are
|
||||
// returned if they related values are defined in req: "net.host.port",
|
||||
// "net.sock.peer.addr", "net.sock.peer.port", "http.user_agent", "enduser.id",
|
||||
// "http.client_ip".
|
||||
func HTTPServerRequest(server string, req *http.Request) []attribute.KeyValue {
|
||||
return hc.ServerRequest(server, req)
|
||||
}
|
||||
|
||||
// HTTPServerRequestMetrics returns metric attributes for an HTTP request received by a
|
||||
// server.
|
||||
//
|
||||
// The server must be the primary server name if it is known. For example this
|
||||
// would be the ServerName directive
|
||||
// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache
|
||||
// server, and the server_name directive
|
||||
// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an
|
||||
// nginx server. More generically, the primary server name would be the host
|
||||
// header value that matches the default virtual host of an HTTP server. It
|
||||
// should include the host identifier and if a port is used to route to the
|
||||
// server that port identifier should be included as an appropriate port
|
||||
// suffix.
|
||||
//
|
||||
// If the primary server name is not known, server should be an empty string.
|
||||
// The req Host will be used to determine the server instead.
|
||||
//
|
||||
// The following attributes are always returned: "http.method", "http.scheme",
|
||||
// "http.flavor", "net.host.name". The following attributes are
|
||||
// returned if they related values are defined in req: "net.host.port".
|
||||
func HTTPServerRequestMetrics(server string, req *http.Request) []attribute.KeyValue {
|
||||
return hc.ServerRequestMetrics(server, req)
|
||||
}
|
||||
|
||||
// HTTPServerStatus returns a span status code and message for an HTTP status code
|
||||
// value returned by a server. Status codes in the 400-499 range are not
|
||||
// returned as errors.
|
||||
func HTTPServerStatus(code int) (codes.Code, string) {
|
||||
return hc.ServerStatus(code)
|
||||
}
|
||||
|
||||
// HTTPRequestHeader returns the contents of h as attributes.
|
||||
//
|
||||
// Instrumentation should require an explicit configuration of which headers to
|
||||
// captured and then prune what they pass here. Including all headers can be a
|
||||
// security risk - explicit configuration helps avoid leaking sensitive
|
||||
// information.
|
||||
//
|
||||
// The User-Agent header is already captured in the http.user_agent attribute
|
||||
// from ClientRequest and ServerRequest. Instrumentation may provide an option
|
||||
// to capture that header here even though it is not recommended. Otherwise,
|
||||
// instrumentation should filter that out of what is passed.
|
||||
func HTTPRequestHeader(h http.Header) []attribute.KeyValue {
|
||||
return hc.RequestHeader(h)
|
||||
}
|
||||
|
||||
// HTTPResponseHeader returns the contents of h as attributes.
|
||||
//
|
||||
// Instrumentation should require an explicit configuration of which headers to
|
||||
// captured and then prune what they pass here. Including all headers can be a
|
||||
// security risk - explicit configuration helps avoid leaking sensitive
|
||||
// information.
|
||||
//
|
||||
// The User-Agent header is already captured in the http.user_agent attribute
|
||||
// from ClientRequest and ServerRequest. Instrumentation may provide an option
|
||||
// to capture that header here even though it is not recommended. Otherwise,
|
||||
// instrumentation should filter that out of what is passed.
|
||||
func HTTPResponseHeader(h http.Header) []attribute.KeyValue {
|
||||
return hc.ResponseHeader(h)
|
||||
}
|
||||
|
||||
// httpConv are the HTTP semantic convention attributes defined for a version
|
||||
// of the OpenTelemetry specification.
|
||||
type httpConv struct {
|
||||
NetConv *netConv
|
||||
|
||||
EnduserIDKey attribute.Key
|
||||
HTTPClientIPKey attribute.Key
|
||||
HTTPFlavorKey attribute.Key
|
||||
HTTPMethodKey attribute.Key
|
||||
HTTPRequestContentLengthKey attribute.Key
|
||||
HTTPResponseContentLengthKey attribute.Key
|
||||
HTTPRouteKey attribute.Key
|
||||
HTTPSchemeHTTP attribute.KeyValue
|
||||
HTTPSchemeHTTPS attribute.KeyValue
|
||||
HTTPStatusCodeKey attribute.Key
|
||||
HTTPTargetKey attribute.Key
|
||||
HTTPURLKey attribute.Key
|
||||
HTTPUserAgentKey attribute.Key
|
||||
}
|
||||
|
||||
var hc = &httpConv{
|
||||
NetConv: nc,
|
||||
|
||||
EnduserIDKey: semconv.EnduserIDKey,
|
||||
HTTPClientIPKey: semconv.HTTPClientIPKey,
|
||||
HTTPFlavorKey: semconv.HTTPFlavorKey,
|
||||
HTTPMethodKey: semconv.HTTPMethodKey,
|
||||
HTTPRequestContentLengthKey: semconv.HTTPRequestContentLengthKey,
|
||||
HTTPResponseContentLengthKey: semconv.HTTPResponseContentLengthKey,
|
||||
HTTPRouteKey: semconv.HTTPRouteKey,
|
||||
HTTPSchemeHTTP: semconv.HTTPSchemeHTTP,
|
||||
HTTPSchemeHTTPS: semconv.HTTPSchemeHTTPS,
|
||||
HTTPStatusCodeKey: semconv.HTTPStatusCodeKey,
|
||||
HTTPTargetKey: semconv.HTTPTargetKey,
|
||||
HTTPURLKey: semconv.HTTPURLKey,
|
||||
HTTPUserAgentKey: semconv.HTTPUserAgentKey,
|
||||
}
|
||||
|
||||
// ClientResponse returns attributes for an HTTP response received by a client
|
||||
// from a server. The following attributes are returned if the related values
|
||||
// are defined in resp: "http.status.code", "http.response_content_length".
|
||||
//
|
||||
// This does not add all OpenTelemetry required attributes for an HTTP event,
|
||||
// it assumes ClientRequest was used to create the span with a complete set of
|
||||
// attributes. If a complete set of attributes can be generated using the
|
||||
// request contained in resp. For example:
|
||||
//
|
||||
// append(ClientResponse(resp), ClientRequest(resp.Request)...)
|
||||
func (c *httpConv) ClientResponse(resp *http.Response) []attribute.KeyValue {
|
||||
var n int
|
||||
if resp.StatusCode > 0 {
|
||||
n++
|
||||
}
|
||||
if resp.ContentLength > 0 {
|
||||
n++
|
||||
}
|
||||
|
||||
attrs := make([]attribute.KeyValue, 0, n)
|
||||
if resp.StatusCode > 0 {
|
||||
attrs = append(attrs, c.HTTPStatusCodeKey.Int(resp.StatusCode))
|
||||
}
|
||||
if resp.ContentLength > 0 {
|
||||
attrs = append(attrs, c.HTTPResponseContentLengthKey.Int(int(resp.ContentLength)))
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
// ClientRequest returns attributes for an HTTP request made by a client. The
|
||||
// following attributes are always returned: "http.url", "http.flavor",
|
||||
// "http.method", "net.peer.name". The following attributes are returned if the
|
||||
// related values are defined in req: "net.peer.port", "http.user_agent",
|
||||
// "http.request_content_length", "enduser.id".
|
||||
func (c *httpConv) ClientRequest(req *http.Request) []attribute.KeyValue {
|
||||
n := 3 // URL, peer name, proto, and method.
|
||||
var h string
|
||||
if req.URL != nil {
|
||||
h = req.URL.Host
|
||||
}
|
||||
peer, p := firstHostPort(h, req.Header.Get("Host"))
|
||||
port := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", p)
|
||||
if port > 0 {
|
||||
n++
|
||||
}
|
||||
useragent := req.UserAgent()
|
||||
if useragent != "" {
|
||||
n++
|
||||
}
|
||||
if req.ContentLength > 0 {
|
||||
n++
|
||||
}
|
||||
userID, _, hasUserID := req.BasicAuth()
|
||||
if hasUserID {
|
||||
n++
|
||||
}
|
||||
attrs := make([]attribute.KeyValue, 0, n)
|
||||
|
||||
attrs = append(attrs, c.method(req.Method))
|
||||
attrs = append(attrs, c.flavor(req.Proto))
|
||||
|
||||
var u string
|
||||
if req.URL != nil {
|
||||
// Remove any username/password info that may be in the URL.
|
||||
userinfo := req.URL.User
|
||||
req.URL.User = nil
|
||||
u = req.URL.String()
|
||||
// Restore any username/password info that was removed.
|
||||
req.URL.User = userinfo
|
||||
}
|
||||
attrs = append(attrs, c.HTTPURLKey.String(u))
|
||||
|
||||
attrs = append(attrs, c.NetConv.PeerName(peer))
|
||||
if port > 0 {
|
||||
attrs = append(attrs, c.NetConv.PeerPort(port))
|
||||
}
|
||||
|
||||
if useragent != "" {
|
||||
attrs = append(attrs, c.HTTPUserAgentKey.String(useragent))
|
||||
}
|
||||
|
||||
if l := req.ContentLength; l > 0 {
|
||||
attrs = append(attrs, c.HTTPRequestContentLengthKey.Int64(l))
|
||||
}
|
||||
|
||||
if hasUserID {
|
||||
attrs = append(attrs, c.EnduserIDKey.String(userID))
|
||||
}
|
||||
|
||||
return attrs
|
||||
}
|
||||
|
||||
// ServerRequest returns attributes for an HTTP request received by a server.
|
||||
//
|
||||
// The server must be the primary server name if it is known. For example this
|
||||
// would be the ServerName directive
|
||||
// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache
|
||||
// server, and the server_name directive
|
||||
// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an
|
||||
// nginx server. More generically, the primary server name would be the host
|
||||
// header value that matches the default virtual host of an HTTP server. It
|
||||
// should include the host identifier and if a port is used to route to the
|
||||
// server that port identifier should be included as an appropriate port
|
||||
// suffix.
|
||||
//
|
||||
// If the primary server name is not known, server should be an empty string.
|
||||
// The req Host will be used to determine the server instead.
|
||||
//
|
||||
// The following attributes are always returned: "http.method", "http.scheme",
|
||||
// "http.flavor", "http.target", "net.host.name". The following attributes are
|
||||
// returned if they related values are defined in req: "net.host.port",
|
||||
// "net.sock.peer.addr", "net.sock.peer.port", "http.user_agent", "enduser.id",
|
||||
// "http.client_ip".
|
||||
func (c *httpConv) ServerRequest(server string, req *http.Request) []attribute.KeyValue {
|
||||
// TODO: This currently does not add the specification required
|
||||
// `http.target` attribute. It has too high of a cardinality to safely be
|
||||
// added. An alternate should be added, or this comment removed, when it is
|
||||
// addressed by the specification. If it is ultimately decided to continue
|
||||
// not including the attribute, the HTTPTargetKey field of the httpConv
|
||||
// should be removed as well.
|
||||
|
||||
n := 4 // Method, scheme, proto, and host name.
|
||||
var host string
|
||||
var p int
|
||||
if server == "" {
|
||||
host, p = splitHostPort(req.Host)
|
||||
} else {
|
||||
// Prioritize the primary server name.
|
||||
host, p = splitHostPort(server)
|
||||
if p < 0 {
|
||||
_, p = splitHostPort(req.Host)
|
||||
}
|
||||
}
|
||||
hostPort := requiredHTTPPort(req.TLS != nil, p)
|
||||
if hostPort > 0 {
|
||||
n++
|
||||
}
|
||||
peer, peerPort := splitHostPort(req.RemoteAddr)
|
||||
if peer != "" {
|
||||
n++
|
||||
if peerPort > 0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
useragent := req.UserAgent()
|
||||
if useragent != "" {
|
||||
n++
|
||||
}
|
||||
userID, _, hasUserID := req.BasicAuth()
|
||||
if hasUserID {
|
||||
n++
|
||||
}
|
||||
clientIP := serverClientIP(req.Header.Get("X-Forwarded-For"))
|
||||
if clientIP != "" {
|
||||
n++
|
||||
}
|
||||
attrs := make([]attribute.KeyValue, 0, n)
|
||||
|
||||
attrs = append(attrs, c.method(req.Method))
|
||||
attrs = append(attrs, c.scheme(req.TLS != nil))
|
||||
attrs = append(attrs, c.flavor(req.Proto))
|
||||
attrs = append(attrs, c.NetConv.HostName(host))
|
||||
|
||||
if hostPort > 0 {
|
||||
attrs = append(attrs, c.NetConv.HostPort(hostPort))
|
||||
}
|
||||
|
||||
if peer != "" {
|
||||
// The Go HTTP server sets RemoteAddr to "IP:port", this will not be a
|
||||
// file-path that would be interpreted with a sock family.
|
||||
attrs = append(attrs, c.NetConv.SockPeerAddr(peer))
|
||||
if peerPort > 0 {
|
||||
attrs = append(attrs, c.NetConv.SockPeerPort(peerPort))
|
||||
}
|
||||
}
|
||||
|
||||
if useragent != "" {
|
||||
attrs = append(attrs, c.HTTPUserAgentKey.String(useragent))
|
||||
}
|
||||
|
||||
if hasUserID {
|
||||
attrs = append(attrs, c.EnduserIDKey.String(userID))
|
||||
}
|
||||
|
||||
if clientIP != "" {
|
||||
attrs = append(attrs, c.HTTPClientIPKey.String(clientIP))
|
||||
}
|
||||
|
||||
return attrs
|
||||
}
|
||||
|
||||
// ServerRequestMetrics returns metric attributes for an HTTP request received
|
||||
// by a server.
|
||||
//
|
||||
// The server must be the primary server name if it is known. For example this
|
||||
// would be the ServerName directive
|
||||
// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache
|
||||
// server, and the server_name directive
|
||||
// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an
|
||||
// nginx server. More generically, the primary server name would be the host
|
||||
// header value that matches the default virtual host of an HTTP server. It
|
||||
// should include the host identifier and if a port is used to route to the
|
||||
// server that port identifier should be included as an appropriate port
|
||||
// suffix.
|
||||
//
|
||||
// If the primary server name is not known, server should be an empty string.
|
||||
// The req Host will be used to determine the server instead.
|
||||
//
|
||||
// The following attributes are always returned: "http.method", "http.scheme",
|
||||
// "http.flavor", "net.host.name". The following attributes are
|
||||
// returned if they related values are defined in req: "net.host.port".
|
||||
func (c *httpConv) ServerRequestMetrics(server string, req *http.Request) []attribute.KeyValue {
|
||||
// TODO: This currently does not add the specification required
|
||||
// `http.target` attribute. It has too high of a cardinality to safely be
|
||||
// added. An alternate should be added, or this comment removed, when it is
|
||||
// addressed by the specification. If it is ultimately decided to continue
|
||||
// not including the attribute, the HTTPTargetKey field of the httpConv
|
||||
// should be removed as well.
|
||||
|
||||
n := 4 // Method, scheme, proto, and host name.
|
||||
var host string
|
||||
var p int
|
||||
if server == "" {
|
||||
host, p = splitHostPort(req.Host)
|
||||
} else {
|
||||
// Prioritize the primary server name.
|
||||
host, p = splitHostPort(server)
|
||||
if p < 0 {
|
||||
_, p = splitHostPort(req.Host)
|
||||
}
|
||||
}
|
||||
hostPort := requiredHTTPPort(req.TLS != nil, p)
|
||||
if hostPort > 0 {
|
||||
n++
|
||||
}
|
||||
attrs := make([]attribute.KeyValue, 0, n)
|
||||
|
||||
attrs = append(attrs, c.methodMetric(req.Method))
|
||||
attrs = append(attrs, c.scheme(req.TLS != nil))
|
||||
attrs = append(attrs, c.flavor(req.Proto))
|
||||
attrs = append(attrs, c.NetConv.HostName(host))
|
||||
|
||||
if hostPort > 0 {
|
||||
attrs = append(attrs, c.NetConv.HostPort(hostPort))
|
||||
}
|
||||
|
||||
return attrs
|
||||
}
|
||||
|
||||
func (c *httpConv) method(method string) attribute.KeyValue {
|
||||
if method == "" {
|
||||
return c.HTTPMethodKey.String(http.MethodGet)
|
||||
}
|
||||
return c.HTTPMethodKey.String(method)
|
||||
}
|
||||
|
||||
func (c *httpConv) methodMetric(method string) attribute.KeyValue {
|
||||
method = strings.ToUpper(method)
|
||||
switch method {
|
||||
case http.MethodConnect, http.MethodDelete, http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPatch, http.MethodPost, http.MethodPut, http.MethodTrace:
|
||||
default:
|
||||
method = "_OTHER"
|
||||
}
|
||||
return c.HTTPMethodKey.String(method)
|
||||
}
|
||||
|
||||
func (c *httpConv) scheme(https bool) attribute.KeyValue { // nolint:revive
|
||||
if https {
|
||||
return c.HTTPSchemeHTTPS
|
||||
}
|
||||
return c.HTTPSchemeHTTP
|
||||
}
|
||||
|
||||
func (c *httpConv) flavor(proto string) attribute.KeyValue {
|
||||
switch proto {
|
||||
case "HTTP/1.0":
|
||||
return c.HTTPFlavorKey.String("1.0")
|
||||
case "HTTP/1.1":
|
||||
return c.HTTPFlavorKey.String("1.1")
|
||||
case "HTTP/2":
|
||||
return c.HTTPFlavorKey.String("2.0")
|
||||
case "HTTP/3":
|
||||
return c.HTTPFlavorKey.String("3.0")
|
||||
default:
|
||||
return c.HTTPFlavorKey.String(proto)
|
||||
}
|
||||
}
|
||||
|
||||
func serverClientIP(xForwardedFor string) string {
|
||||
if idx := strings.Index(xForwardedFor, ","); idx >= 0 {
|
||||
xForwardedFor = xForwardedFor[:idx]
|
||||
}
|
||||
return xForwardedFor
|
||||
}
|
||||
|
||||
func requiredHTTPPort(https bool, port int) int { // nolint:revive
|
||||
if https {
|
||||
if port > 0 && port != 443 {
|
||||
return port
|
||||
}
|
||||
} else {
|
||||
if port > 0 && port != 80 {
|
||||
return port
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Return the request host and port from the first non-empty source.
|
||||
func firstHostPort(source ...string) (host string, port int) {
|
||||
for _, hostport := range source {
|
||||
host, port = splitHostPort(hostport)
|
||||
if host != "" || port > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// RequestHeader returns the contents of h as OpenTelemetry attributes.
|
||||
func (c *httpConv) RequestHeader(h http.Header) []attribute.KeyValue {
|
||||
return c.header("http.request.header", h)
|
||||
}
|
||||
|
||||
// ResponseHeader returns the contents of h as OpenTelemetry attributes.
|
||||
func (c *httpConv) ResponseHeader(h http.Header) []attribute.KeyValue {
|
||||
return c.header("http.response.header", h)
|
||||
}
|
||||
|
||||
func (c *httpConv) header(prefix string, h http.Header) []attribute.KeyValue {
|
||||
key := func(k string) attribute.Key {
|
||||
k = strings.ToLower(k)
|
||||
k = strings.ReplaceAll(k, "-", "_")
|
||||
k = fmt.Sprintf("%s.%s", prefix, k)
|
||||
return attribute.Key(k)
|
||||
}
|
||||
|
||||
attrs := make([]attribute.KeyValue, 0, len(h))
|
||||
for k, v := range h {
|
||||
attrs = append(attrs, key(k).StringSlice(v))
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
// ClientStatus returns a span status code and message for an HTTP status code
|
||||
// value received by a client.
|
||||
func (c *httpConv) ClientStatus(code int) (codes.Code, string) {
|
||||
if code < 100 || code >= 600 {
|
||||
return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code)
|
||||
}
|
||||
if code >= 400 {
|
||||
return codes.Error, ""
|
||||
}
|
||||
return codes.Unset, ""
|
||||
}
|
||||
|
||||
// ServerStatus returns a span status code and message for an HTTP status code
|
||||
// value returned by a server. Status codes in the 400-499 range are not
|
||||
// returned as errors.
|
||||
func (c *httpConv) ServerStatus(code int) (codes.Code, string) {
|
||||
if code < 100 || code >= 600 {
|
||||
return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code)
|
||||
}
|
||||
if code >= 500 {
|
||||
return codes.Error, ""
|
||||
}
|
||||
return codes.Unset, ""
|
||||
}
|
||||
Generated
Vendored
+368
@@ -0,0 +1,368 @@
|
||||
// Code created by gotmpl. DO NOT MODIFY.
|
||||
// source: internal/shared/semconvutil/netconv.go.tmpl
|
||||
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package semconvutil // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil"
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
|
||||
)
|
||||
|
||||
// NetTransport returns a trace attribute describing the transport protocol of the
|
||||
// passed network. See the net.Dial for information about acceptable network
|
||||
// values.
|
||||
func NetTransport(network string) attribute.KeyValue {
|
||||
return nc.Transport(network)
|
||||
}
|
||||
|
||||
// NetClient returns trace attributes for a client network connection to address.
|
||||
// See net.Dial for information about acceptable address values, address should
|
||||
// be the same as the one used to create conn. If conn is nil, only network
|
||||
// peer attributes will be returned that describe address. Otherwise, the
|
||||
// socket level information about conn will also be included.
|
||||
func NetClient(address string, conn net.Conn) []attribute.KeyValue {
|
||||
return nc.Client(address, conn)
|
||||
}
|
||||
|
||||
// NetServer returns trace attributes for a network listener listening at address.
|
||||
// See net.Listen for information about acceptable address values, address
|
||||
// should be the same as the one used to create ln. If ln is nil, only network
|
||||
// host attributes will be returned that describe address. Otherwise, the
|
||||
// socket level information about ln will also be included.
|
||||
func NetServer(address string, ln net.Listener) []attribute.KeyValue {
|
||||
return nc.Server(address, ln)
|
||||
}
|
||||
|
||||
// netConv are the network semantic convention attributes defined for a version
|
||||
// of the OpenTelemetry specification.
|
||||
type netConv struct {
|
||||
NetHostNameKey attribute.Key
|
||||
NetHostPortKey attribute.Key
|
||||
NetPeerNameKey attribute.Key
|
||||
NetPeerPortKey attribute.Key
|
||||
NetSockFamilyKey attribute.Key
|
||||
NetSockPeerAddrKey attribute.Key
|
||||
NetSockPeerPortKey attribute.Key
|
||||
NetSockHostAddrKey attribute.Key
|
||||
NetSockHostPortKey attribute.Key
|
||||
NetTransportOther attribute.KeyValue
|
||||
NetTransportTCP attribute.KeyValue
|
||||
NetTransportUDP attribute.KeyValue
|
||||
NetTransportInProc attribute.KeyValue
|
||||
}
|
||||
|
||||
var nc = &netConv{
|
||||
NetHostNameKey: semconv.NetHostNameKey,
|
||||
NetHostPortKey: semconv.NetHostPortKey,
|
||||
NetPeerNameKey: semconv.NetPeerNameKey,
|
||||
NetPeerPortKey: semconv.NetPeerPortKey,
|
||||
NetSockFamilyKey: semconv.NetSockFamilyKey,
|
||||
NetSockPeerAddrKey: semconv.NetSockPeerAddrKey,
|
||||
NetSockPeerPortKey: semconv.NetSockPeerPortKey,
|
||||
NetSockHostAddrKey: semconv.NetSockHostAddrKey,
|
||||
NetSockHostPortKey: semconv.NetSockHostPortKey,
|
||||
NetTransportOther: semconv.NetTransportOther,
|
||||
NetTransportTCP: semconv.NetTransportTCP,
|
||||
NetTransportUDP: semconv.NetTransportUDP,
|
||||
NetTransportInProc: semconv.NetTransportInProc,
|
||||
}
|
||||
|
||||
func (c *netConv) Transport(network string) attribute.KeyValue {
|
||||
switch network {
|
||||
case "tcp", "tcp4", "tcp6":
|
||||
return c.NetTransportTCP
|
||||
case "udp", "udp4", "udp6":
|
||||
return c.NetTransportUDP
|
||||
case "unix", "unixgram", "unixpacket":
|
||||
return c.NetTransportInProc
|
||||
default:
|
||||
// "ip:*", "ip4:*", and "ip6:*" all are considered other.
|
||||
return c.NetTransportOther
|
||||
}
|
||||
}
|
||||
|
||||
// Host returns attributes for a network host address.
|
||||
func (c *netConv) Host(address string) []attribute.KeyValue {
|
||||
h, p := splitHostPort(address)
|
||||
var n int
|
||||
if h != "" {
|
||||
n++
|
||||
if p > 0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
attrs := make([]attribute.KeyValue, 0, n)
|
||||
attrs = append(attrs, c.HostName(h))
|
||||
if p > 0 {
|
||||
attrs = append(attrs, c.HostPort(int(p)))
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
// Server returns attributes for a network listener listening at address. See
|
||||
// net.Listen for information about acceptable address values, address should
|
||||
// be the same as the one used to create ln. If ln is nil, only network host
|
||||
// attributes will be returned that describe address. Otherwise, the socket
|
||||
// level information about ln will also be included.
|
||||
func (c *netConv) Server(address string, ln net.Listener) []attribute.KeyValue {
|
||||
if ln == nil {
|
||||
return c.Host(address)
|
||||
}
|
||||
|
||||
lAddr := ln.Addr()
|
||||
if lAddr == nil {
|
||||
return c.Host(address)
|
||||
}
|
||||
|
||||
hostName, hostPort := splitHostPort(address)
|
||||
sockHostAddr, sockHostPort := splitHostPort(lAddr.String())
|
||||
network := lAddr.Network()
|
||||
sockFamily := family(network, sockHostAddr)
|
||||
|
||||
n := nonZeroStr(hostName, network, sockHostAddr, sockFamily)
|
||||
n += positiveInt(hostPort, sockHostPort)
|
||||
attr := make([]attribute.KeyValue, 0, n)
|
||||
if hostName != "" {
|
||||
attr = append(attr, c.HostName(hostName))
|
||||
if hostPort > 0 {
|
||||
// Only if net.host.name is set should net.host.port be.
|
||||
attr = append(attr, c.HostPort(hostPort))
|
||||
}
|
||||
}
|
||||
if network != "" {
|
||||
attr = append(attr, c.Transport(network))
|
||||
}
|
||||
if sockFamily != "" {
|
||||
attr = append(attr, c.NetSockFamilyKey.String(sockFamily))
|
||||
}
|
||||
if sockHostAddr != "" {
|
||||
attr = append(attr, c.NetSockHostAddrKey.String(sockHostAddr))
|
||||
if sockHostPort > 0 {
|
||||
// Only if net.sock.host.addr is set should net.sock.host.port be.
|
||||
attr = append(attr, c.NetSockHostPortKey.Int(sockHostPort))
|
||||
}
|
||||
}
|
||||
return attr
|
||||
}
|
||||
|
||||
func (c *netConv) HostName(name string) attribute.KeyValue {
|
||||
return c.NetHostNameKey.String(name)
|
||||
}
|
||||
|
||||
func (c *netConv) HostPort(port int) attribute.KeyValue {
|
||||
return c.NetHostPortKey.Int(port)
|
||||
}
|
||||
|
||||
// Client returns attributes for a client network connection to address. See
|
||||
// net.Dial for information about acceptable address values, address should be
|
||||
// the same as the one used to create conn. If conn is nil, only network peer
|
||||
// attributes will be returned that describe address. Otherwise, the socket
|
||||
// level information about conn will also be included.
|
||||
func (c *netConv) Client(address string, conn net.Conn) []attribute.KeyValue {
|
||||
if conn == nil {
|
||||
return c.Peer(address)
|
||||
}
|
||||
|
||||
lAddr, rAddr := conn.LocalAddr(), conn.RemoteAddr()
|
||||
|
||||
var network string
|
||||
switch {
|
||||
case lAddr != nil:
|
||||
network = lAddr.Network()
|
||||
case rAddr != nil:
|
||||
network = rAddr.Network()
|
||||
default:
|
||||
return c.Peer(address)
|
||||
}
|
||||
|
||||
peerName, peerPort := splitHostPort(address)
|
||||
var (
|
||||
sockFamily string
|
||||
sockPeerAddr string
|
||||
sockPeerPort int
|
||||
sockHostAddr string
|
||||
sockHostPort int
|
||||
)
|
||||
|
||||
if lAddr != nil {
|
||||
sockHostAddr, sockHostPort = splitHostPort(lAddr.String())
|
||||
}
|
||||
|
||||
if rAddr != nil {
|
||||
sockPeerAddr, sockPeerPort = splitHostPort(rAddr.String())
|
||||
}
|
||||
|
||||
switch {
|
||||
case sockHostAddr != "":
|
||||
sockFamily = family(network, sockHostAddr)
|
||||
case sockPeerAddr != "":
|
||||
sockFamily = family(network, sockPeerAddr)
|
||||
}
|
||||
|
||||
n := nonZeroStr(peerName, network, sockPeerAddr, sockHostAddr, sockFamily)
|
||||
n += positiveInt(peerPort, sockPeerPort, sockHostPort)
|
||||
attr := make([]attribute.KeyValue, 0, n)
|
||||
if peerName != "" {
|
||||
attr = append(attr, c.PeerName(peerName))
|
||||
if peerPort > 0 {
|
||||
// Only if net.peer.name is set should net.peer.port be.
|
||||
attr = append(attr, c.PeerPort(peerPort))
|
||||
}
|
||||
}
|
||||
if network != "" {
|
||||
attr = append(attr, c.Transport(network))
|
||||
}
|
||||
if sockFamily != "" {
|
||||
attr = append(attr, c.NetSockFamilyKey.String(sockFamily))
|
||||
}
|
||||
if sockPeerAddr != "" {
|
||||
attr = append(attr, c.NetSockPeerAddrKey.String(sockPeerAddr))
|
||||
if sockPeerPort > 0 {
|
||||
// Only if net.sock.peer.addr is set should net.sock.peer.port be.
|
||||
attr = append(attr, c.NetSockPeerPortKey.Int(sockPeerPort))
|
||||
}
|
||||
}
|
||||
if sockHostAddr != "" {
|
||||
attr = append(attr, c.NetSockHostAddrKey.String(sockHostAddr))
|
||||
if sockHostPort > 0 {
|
||||
// Only if net.sock.host.addr is set should net.sock.host.port be.
|
||||
attr = append(attr, c.NetSockHostPortKey.Int(sockHostPort))
|
||||
}
|
||||
}
|
||||
return attr
|
||||
}
|
||||
|
||||
func family(network, address string) string {
|
||||
switch network {
|
||||
case "unix", "unixgram", "unixpacket":
|
||||
return "unix"
|
||||
default:
|
||||
if ip := net.ParseIP(address); ip != nil {
|
||||
if ip.To4() == nil {
|
||||
return "inet6"
|
||||
}
|
||||
return "inet"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func nonZeroStr(strs ...string) int {
|
||||
var n int
|
||||
for _, str := range strs {
|
||||
if str != "" {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func positiveInt(ints ...int) int {
|
||||
var n int
|
||||
for _, i := range ints {
|
||||
if i > 0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// Peer returns attributes for a network peer address.
|
||||
func (c *netConv) Peer(address string) []attribute.KeyValue {
|
||||
h, p := splitHostPort(address)
|
||||
var n int
|
||||
if h != "" {
|
||||
n++
|
||||
if p > 0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
attrs := make([]attribute.KeyValue, 0, n)
|
||||
attrs = append(attrs, c.PeerName(h))
|
||||
if p > 0 {
|
||||
attrs = append(attrs, c.PeerPort(int(p)))
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
func (c *netConv) PeerName(name string) attribute.KeyValue {
|
||||
return c.NetPeerNameKey.String(name)
|
||||
}
|
||||
|
||||
func (c *netConv) PeerPort(port int) attribute.KeyValue {
|
||||
return c.NetPeerPortKey.Int(port)
|
||||
}
|
||||
|
||||
func (c *netConv) SockPeerAddr(addr string) attribute.KeyValue {
|
||||
return c.NetSockPeerAddrKey.String(addr)
|
||||
}
|
||||
|
||||
func (c *netConv) SockPeerPort(port int) attribute.KeyValue {
|
||||
return c.NetSockPeerPortKey.Int(port)
|
||||
}
|
||||
|
||||
// splitHostPort splits a network address hostport of the form "host",
|
||||
// "host%zone", "[host]", "[host%zone], "host:port", "host%zone:port",
|
||||
// "[host]:port", "[host%zone]:port", or ":port" into host or host%zone and
|
||||
// port.
|
||||
//
|
||||
// An empty host is returned if it is not provided or unparsable. A negative
|
||||
// port is returned if it is not provided or unparsable.
|
||||
func splitHostPort(hostport string) (host string, port int) {
|
||||
port = -1
|
||||
|
||||
if strings.HasPrefix(hostport, "[") {
|
||||
addrEnd := strings.LastIndex(hostport, "]")
|
||||
if addrEnd < 0 {
|
||||
// Invalid hostport.
|
||||
return
|
||||
}
|
||||
if i := strings.LastIndex(hostport[addrEnd:], ":"); i < 0 {
|
||||
host = hostport[1:addrEnd]
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if i := strings.LastIndex(hostport, ":"); i < 0 {
|
||||
host = hostport
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
host, pStr, err := net.SplitHostPort(hostport)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
p, err := strconv.ParseUint(pStr, 10, 16)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return host, int(p)
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package tracing
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
traceapi "go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// TracerProvider is an alias for OpenTelemetry's TracerProvider interface.
|
||||
type TracerProvider = traceapi.TracerProvider
|
||||
|
||||
// Propagator is an alias for OpenTelemetry's TextMapPropagator interface.
|
||||
type Propagator = propagation.TextMapPropagator
|
||||
|
||||
// Provider extends TracerProvider with a Shutdown method for graceful cleanup.
|
||||
type Provider interface {
|
||||
TracerProvider
|
||||
// Shutdown gracefully shuts down the provider, flushing any pending spans.
|
||||
Shutdown(ctx context.Context) error
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package tracing
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"go.opentelemetry.io/otel/trace/noop"
|
||||
)
|
||||
|
||||
// NoopProvider is a no-op implementation of the Provider interface.
|
||||
// It provides a tracer that performs no operations, useful when tracing is disabled.
|
||||
type NoopProvider struct {
|
||||
Provider
|
||||
}
|
||||
|
||||
// NewNoopProvider creates a new no-op tracer provider.
|
||||
func NewNoopProvider() NoopProvider {
|
||||
return NoopProvider{}
|
||||
}
|
||||
|
||||
// Tracer returns a no-op tracer that performs no operations.
|
||||
func (n NoopProvider) Tracer(name string, options ...trace.TracerOption) trace.Tracer {
|
||||
return noop.Tracer{}
|
||||
}
|
||||
|
||||
// Shutdown returns nil as no resources need to be cleaned up.
|
||||
func (n NoopProvider) Shutdown(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsNoop checks if the given TracerProvider is a NoopProvider.
|
||||
func IsNoop(provider TracerProvider) bool {
|
||||
_, isNoop := provider.(NoopProvider)
|
||||
return isNoop
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package tracing
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/go-logr/stdr"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
|
||||
)
|
||||
|
||||
// DefaultPropagator is the default text map propagator using W3C Trace Context.
|
||||
var DefaultPropagator Propagator = propagation.TraceContext{}
|
||||
|
||||
// DefaultProvider is the global default tracer provider, initially set to a no-op provider.
|
||||
var DefaultProvider TracerProvider = NewNoopProvider()
|
||||
|
||||
// RequestId is the attribute key used to store the request ID in spans.
|
||||
const (
|
||||
RequestId = attribute.Key("app.request_id")
|
||||
)
|
||||
|
||||
// NewProviderFromConfiguration creates a new tracer provider from the given configuration.
|
||||
// It returns a no-op provider if tracing is disabled. The provider is configured to export
|
||||
// traces via OTLP over HTTP to the specified address.
|
||||
func NewProviderFromConfiguration(ctx context.Context, logger log.Logger, config Config) (Provider, error) {
|
||||
if !config.Enable {
|
||||
return NewNoopProvider(), nil
|
||||
}
|
||||
|
||||
stdLogger := log.StdLoggerWithLevel(logger, log.InfoLevel, log.String("worker", "tracer"))
|
||||
otel.SetLogger(stdr.New(stdLogger))
|
||||
|
||||
exporter, err := otlptracehttp.New(
|
||||
ctx,
|
||||
otlptracehttp.WithEndpoint(config.Address),
|
||||
otlptracehttp.WithInsecure(),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "new otlp http exporter")
|
||||
}
|
||||
|
||||
attributes := []attribute.KeyValue{
|
||||
semconv.DeploymentEnvironment(config.Environment),
|
||||
semconv.ServiceVersion(config.ModuleVersion),
|
||||
semconv.ServiceName(config.ModuleName),
|
||||
semconv.ServiceInstanceID(config.InstanceId),
|
||||
}
|
||||
for key, value := range config.Attributes {
|
||||
attributes = append(attributes, attribute.String(key, value))
|
||||
}
|
||||
res, err := resource.Merge(
|
||||
resource.Default(),
|
||||
resource.NewWithAttributes(
|
||||
semconv.SchemaURL,
|
||||
attributes...,
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "new resource")
|
||||
}
|
||||
|
||||
provider := sdktrace.NewTracerProvider(
|
||||
sdktrace.WithBatcher(exporter),
|
||||
sdktrace.WithResource(res),
|
||||
sdktrace.WithSampler(sdktrace.AlwaysSample()),
|
||||
)
|
||||
return provider, nil
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
# Package `sql_tracing`
|
||||
|
||||
Пакет `sql_tracing` предоставляет инструменты трассировки SQL-запросов для PostgreSQL-драйвера `pgx` с использованием OpenTelemetry. Поддерживает автоматическое создание span'ов, запись аргументов и SQL-выражений, а также метрики SQL-операций через `sql_metrics`.
|
||||
|
||||
## Types
|
||||
|
||||
### Tracer
|
||||
|
||||
Структура `Tracer` реализует интерфейс `pgx.QueryTracer` и обеспечивает создание и завершение span'ов при выполнении SQL-запросов. Позволяет гибко настраивать включение SQL-выражений и параметров в span'ы.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewTracer(tracer trace.Tracer, config Config) Tracer`
|
||||
|
||||
Создаёт трейсер.
|
||||
|
||||
#### `(t Tracer) TraceQueryStart(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryStartData) context.Context`
|
||||
|
||||
Создаёт span перед выполнением SQL-запроса. Возвращает новый `context.Context` с активным span.
|
||||
|
||||
#### `(t Tracer) TraceQueryEnd(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryEndData)`
|
||||
|
||||
Завершает span после выполнения SQL-запроса. В случае ошибки (кроме `sql.ErrNoRows`) записывает её в span и устанавливает статус `Error`.
|
||||
|
||||
### Config
|
||||
|
||||
Структура `Config` содержит параметры конфигурации для трассировки SQL-запросов.
|
||||
|
||||
**Fields:**
|
||||
|
||||
#### `Provider tracing.TracerProvider`
|
||||
|
||||
Провайдер трассировки (по умолчанию `tracing.DefaultProvider`)
|
||||
|
||||
#### `EnableStatement bool`
|
||||
|
||||
Включает добавление SQL-выражения в атрибуты span'а
|
||||
|
||||
#### `EnableArgs bool`
|
||||
|
||||
Включает добавление аргументов запроса в атрибуты span'а
|
||||
|
||||
**Methods**
|
||||
|
||||
#### `NewConfig() Config`
|
||||
|
||||
Создаёт конфигурацию трассировки с провайдером по умолчанию.
|
||||
|
||||
#### `(c Config) QueryTracer() pgx.QueryTracer`
|
||||
|
||||
Возвращает либо полноценный трассировщик `Tracer`, либо `noop`, если провайдер трассировки является "заглушкой".
|
||||
|
||||
## Usage
|
||||
|
||||
### Подключение трассировки SQL-запросов
|
||||
|
||||
```go
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/observability/tracing"
|
||||
"github.com/txix-open/isp-kit/observability/sql_tracing"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func setupTracer() pgx.QueryTracer {
|
||||
cfg := sql_tracing.NewConfig()
|
||||
cfg.EnableStatement = true
|
||||
cfg.EnableArgs = true
|
||||
|
||||
return cfg.QueryTracer()
|
||||
}
|
||||
```
|
||||
|
||||
### Регистрация в `pgx` соединении
|
||||
|
||||
```go
|
||||
connConfig := pgx.ConnConfig{ /* ваша конфигурация */ }
|
||||
connConfig.Tracer = setupTracer()
|
||||
```
|
||||
|
||||
Теперь каждый SQL-запрос будет автоматически трассироваться с учётом включённых опций (запрос, параметры, request ID и т.п.).
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
// Package sql_tracing provides pgx v5 query tracing for distributed tracing.
|
||||
package sql_tracing
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/txix-open/isp-kit/observability/tracing"
|
||||
)
|
||||
|
||||
// tracerName identifies the tracer for SQL tracing.
|
||||
const tracerName = "isp-kit/observability/tracing/sql"
|
||||
|
||||
// Config holds the configuration for SQL query tracing.
|
||||
type Config struct {
|
||||
// Provider is the tracer provider used to create tracers.
|
||||
Provider tracing.TracerProvider
|
||||
// EnableStatement determines whether to include SQL statements in spans.
|
||||
EnableStatement bool
|
||||
// EnableArgs determines whether to include query arguments in spans.
|
||||
EnableArgs bool
|
||||
}
|
||||
|
||||
// NewConfig creates a new Config with default values.
|
||||
func NewConfig() Config {
|
||||
return Config{
|
||||
Provider: tracing.DefaultProvider,
|
||||
}
|
||||
}
|
||||
|
||||
// QueryTracer returns a pgx QueryTracer for instrumenting database queries.
|
||||
// It returns a no-op tracer if the provider is a no-op.
|
||||
func (c Config) QueryTracer() pgx.QueryTracer {
|
||||
if tracing.IsNoop(c.Provider) {
|
||||
return noop{}
|
||||
}
|
||||
|
||||
tracer := c.Provider.Tracer(tracerName)
|
||||
return NewTracer(tracer, c)
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package sql_tracing
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// noop is a no-op implementation of pgx.QueryTracer.
|
||||
type noop struct{}
|
||||
|
||||
// TraceQueryStart returns the context unchanged without creating a span.
|
||||
func (n noop) TraceQueryStart(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
|
||||
return ctx
|
||||
}
|
||||
|
||||
// TraceQueryEnd performs no operation.
|
||||
func (n noop) TraceQueryEnd(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryEndData) {
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package sql_tracing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
"github.com/txix-open/isp-kit/observability/tracing"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// QueryParametersKey is the attribute key for storing query arguments.
|
||||
var QueryParametersKey = attribute.Key("pgx.query.parameters")
|
||||
|
||||
// contextKey is used for storing the span in the context.
|
||||
type contextKey struct{}
|
||||
|
||||
// contextKeyValue is the global context key instance.
|
||||
var contextKeyValue = contextKey{}
|
||||
|
||||
// Tracer implements pgx.QueryTracer for tracing SQL queries.
|
||||
type Tracer struct {
|
||||
tracer trace.Tracer
|
||||
config Config
|
||||
}
|
||||
|
||||
// NewTracer creates a new Tracer with the given tracer and configuration.
|
||||
func NewTracer(tracer trace.Tracer, config Config) Tracer {
|
||||
return Tracer{
|
||||
tracer: tracer,
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// TraceQueryStart creates a span for the beginning of a database query.
|
||||
// It extracts the operation label from context or from the SQL statement
|
||||
// (for BEGIN/COMMIT). The span includes the SQL statement and arguments
|
||||
// if configured. Returns the context with the span attached.
|
||||
func (t Tracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
|
||||
label := sql_metrics.OperationLabelFromContext(ctx)
|
||||
if label == "" && strings.HasPrefix(data.SQL, "begin") {
|
||||
label = "BEGIN"
|
||||
}
|
||||
if label == "" && strings.HasPrefix(data.SQL, "commit") {
|
||||
label = "COMMIT"
|
||||
}
|
||||
if label == "" {
|
||||
return ctx
|
||||
}
|
||||
|
||||
attributes := []attribute.KeyValue{
|
||||
tracing.RequestId.String(requestid.FromContext(ctx)),
|
||||
}
|
||||
if t.config.EnableStatement {
|
||||
attributes = append(attributes, semconv.DBStatement(data.SQL))
|
||||
}
|
||||
if t.config.EnableArgs {
|
||||
args := make([]string, 0, len(data.Args))
|
||||
for _, arg := range data.Args {
|
||||
args = append(args, fmt.Sprintf("%+v", arg))
|
||||
}
|
||||
attributes = append(attributes, QueryParametersKey.StringSlice(args))
|
||||
}
|
||||
|
||||
opts := []trace.SpanStartOption{
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(attributes...),
|
||||
}
|
||||
|
||||
spanName := fmt.Sprintf("SQL query %s", label)
|
||||
ctx, span := t.tracer.Start(ctx, spanName, opts...) //nolint:spancheck
|
||||
|
||||
return context.WithValue(ctx, contextKeyValue, span) //nolint:spancheck
|
||||
}
|
||||
|
||||
// TraceQueryEnd ends the span for a database query and records any errors.
|
||||
// It skips recording errors for sql.ErrNoRows.
|
||||
func (t Tracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
|
||||
span, _ := ctx.Value(contextKeyValue).(trace.Span)
|
||||
if span == nil {
|
||||
return
|
||||
}
|
||||
|
||||
err := data.Err
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
|
||||
span.End()
|
||||
}
|
||||
Reference in new issue
Block a user