Documentation
¶
Overview ¶
Package graftel fornece uma interface simplificada para trabalhar com OpenTelemetry em aplicações Go, focando em métricas e logs.
Exemplo básico:
config := graftel.NewConfig("meu-servico").
WithServiceVersion("1.0.0").
WithOTLPEndpoint("http://localhost:4318").
WithInsecure(true)
client, err := graftel.NewClient(config)
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
if err := client.Initialize(ctx); err != nil {
log.Fatal(err)
}
defer client.Shutdown(ctx)
Package graftel fornece helpers para trabalhar com logs OpenTelemetry.
Package graftel fornece helpers para trabalhar com métricas OpenTelemetry.
Index ¶
- func ChiMiddleware(client Client, config MiddlewareConfig) func(http.Handler) http.Handler
- func EchoMiddleware(client Client, config MiddlewareConfig) echo.MiddlewareFunc
- func GetTagsFromContext(ctx context.Context) []attribute.KeyValue
- func GinMiddleware(client Client, config MiddlewareConfig) gin.HandlerFunc
- func HTTPMiddleware(client Client, config MiddlewareConfig) func(http.Handler) http.Handler
- func MergeContextTags(ctx context.Context, additionalTags ...attribute.KeyValue) context.Context
- func StartSpan(ctx context.Context, name string, tags ...attribute.KeyValue) (context.Context, trace.Span)
- func WithSpan(ctx context.Context, name string, fn func(context.Context) error, ...) error
- func WithSpanTiming(ctx context.Context, name string, fn func(context.Context) error, ...) error
- func WithTags(ctx context.Context, tags ...attribute.KeyValue) context.Context
- type Client
- type Config
- func (c *Config) Validate() error
- func (c Config) WithAPIKey(apiKey string) Config
- func (c Config) WithExportTimeout(timeout time.Duration) Config
- func (c Config) WithInsecure(insecure bool) Config
- func (c Config) WithInstanceID(instanceID string) Config
- func (c Config) WithLogExportInterval(interval time.Duration) Config
- func (c Config) WithMetricExportInterval(interval time.Duration) Config
- func (c Config) WithOTLPEndpoint(endpoint string) Config
- func (c Config) WithPrometheusEndpoint(endpoint string) Config
- func (c Config) WithResourceAttribute(key, value string) Config
- func (c Config) WithResourceAttributes(attrs map[string]string) Config
- func (c Config) WithServiceVersion(version string) Config
- type ContextLogger
- func (cl *ContextLogger) Debug(msg string, tags ...attribute.KeyValue)
- func (cl *ContextLogger) Error(msg string, tags ...attribute.KeyValue)
- func (cl *ContextLogger) ErrorWithError(msg string, err error, tags ...attribute.KeyValue)
- func (cl *ContextLogger) Fatal(msg string, tags ...attribute.KeyValue)
- func (cl *ContextLogger) Info(msg string, tags ...attribute.KeyValue)
- func (cl *ContextLogger) Log(level LogLevel, msg string, tags ...attribute.KeyValue)
- func (cl *ContextLogger) LogWithError(level LogLevel, msg string, err error, tags ...attribute.KeyValue)
- func (cl *ContextLogger) LogWithFields(level LogLevel, msg string, fields map[string]interface{}, ...)
- func (cl *ContextLogger) Trace(msg string, tags ...attribute.KeyValue)
- func (cl *ContextLogger) Warn(msg string, tags ...attribute.KeyValue)
- func (cl *ContextLogger) WithTags(tags ...attribute.KeyValue) *ContextLogger
- type Counter
- type ErrInitializationFailed
- type ErrInvalidConfig
- type ErrShutdownFailed
- type Gauge
- type Histogram
- type LogLevel
- type LogsHelper
- type MetricsHelper
- type MiddlewareConfig
- type TracingHelper
- type UpDownCounter
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ChiMiddleware ¶
func EchoMiddleware ¶
func EchoMiddleware(client Client, config MiddlewareConfig) echo.MiddlewareFunc
func GinMiddleware ¶
func GinMiddleware(client Client, config MiddlewareConfig) gin.HandlerFunc
func HTTPMiddleware ¶
func MergeContextTags ¶
func WithSpanTiming ¶
Types ¶
type Client ¶
type Client interface {
// Initialize inicializa o OpenTelemetry com métricas e logs.
// Deve ser chamado antes de usar qualquer funcionalidade.
Initialize(ctx context.Context) error
// Shutdown encerra o cliente OpenTelemetry de forma segura.
// Deve ser chamado ao finalizar a aplicação.
Shutdown(ctx context.Context) error
// GetMeter retorna um Meter para criar métricas.
GetMeter(name string, opts ...otelmetric.MeterOption) otelmetric.Meter
// GetLogger retorna um Logger para criar logs.
GetLogger(name string) otellog.Logger
// GetPrometheusExporter retorna o exporter Prometheus, se configurado.
// Retorna nil se Prometheus não estiver habilitado.
GetPrometheusExporter() *prometheus.Exporter
// NewMetricsHelper cria um helper para facilitar o uso de métricas.
NewMetricsHelper(name string) MetricsHelper
// NewLogsHelper cria um helper para facilitar o uso de logs.
NewLogsHelper(name string) LogsHelper
// GetTracer retorna um Tracer para criar spans e traces.
GetTracer(name string, opts ...trace.TracerOption) trace.Tracer
// NewTracingHelper cria um helper para facilitar o uso de tracing.
NewTracingHelper(name string) TracingHelper
}
Client gerencia a inicialização e uso do OpenTelemetry. É a interface principal para trabalhar com métricas e logs.
type Config ¶
type Config struct {
// ServiceName é o nome do serviço (obrigatório).
ServiceName string
// ServiceVersion é a versão do serviço.
ServiceVersion string
// OTLPEndpoint é o endpoint OTLP para métricas e logs.
// Pode ser configurado via GRAFTEL_OTLP_ENDPOINT ou WithOTLPEndpoint.
// Padrão: http://localhost:4318
OTLPEndpoint string
// APIKey é a chave de API para autenticação (obrigatória se usar autenticação).
// Pode ser configurada via GRAFTEL_API_KEY ou WithAPIKey.
APIKey string
// InstanceID é o ID da instância (opcional).
// Se fornecido, será usado como service.instance.id no resource OpenTelemetry.
// Pode ser configurado via GRAFTEL_INSTANCE_ID ou WithInstanceID.
InstanceID string
// PrometheusEndpoint é o endpoint para expor métricas Prometheus (ex: :8080).
// Se vazio, não expõe endpoint Prometheus.
PrometheusEndpoint string
// ResourceAttributes são atributos adicionais para o resource.
ResourceAttributes map[string]string
// MetricExportInterval é o intervalo de exportação de métricas.
// Padrão: 30 segundos
MetricExportInterval time.Duration
// LogExportInterval é o intervalo de exportação de logs.
// Padrão: 30 segundos
LogExportInterval time.Duration
// ExportTimeout é o timeout para exportação de dados OTLP.
// Padrão: 10 segundos
ExportTimeout time.Duration
// Insecure desabilita TLS (apenas para desenvolvimento local).
Insecure bool
}
Config contém as configurações para inicializar o OpenTelemetry. Use NewConfig para criar uma configuração com valores padrão.
func NewConfig ¶
NewConfig cria uma nova configuração com valores padrão. O serviceName é obrigatório, mas pode ser fornecido via GRAFTEL_SERVICE_NAME. Valores são carregados na seguinte ordem de prioridade: 1. Valores passados via métodos With* (maior prioridade) 2. Variáveis de ambiente GRAFTEL_* 3. Valores padrão
func (*Config) Validate ¶
Validate valida a configuração e retorna um erro se inválida. Define valores padrão se não foram configurados.
func (Config) WithAPIKey ¶
WithAPIKey define a chave de API para autenticação. Se não fornecido, será lido de GRAFTEL_API_KEY.
func (Config) WithExportTimeout ¶
WithExportTimeout define o timeout para exportação de dados OTLP.
func (Config) WithInsecure ¶
WithInsecure desabilita TLS (apenas para desenvolvimento local).
func (Config) WithInstanceID ¶
WithInstanceID define o ID da instância. Este ID será usado como service.instance.id no resource OpenTelemetry. Se não fornecido, será lido de GRAFTEL_INSTANCE_ID.
func (Config) WithLogExportInterval ¶
WithLogExportInterval define o intervalo de exportação de logs.
func (Config) WithMetricExportInterval ¶
WithMetricExportInterval define o intervalo de exportação de métricas.
func (Config) WithOTLPEndpoint ¶
WithOTLPEndpoint define o endpoint OTLP. Se não fornecido, será lido de GRAFTEL_OTLP_ENDPOINT.
func (Config) WithPrometheusEndpoint ¶
WithPrometheusEndpoint define o endpoint para expor métricas Prometheus.
func (Config) WithResourceAttribute ¶
WithResourceAttribute adiciona um atributo ao resource.
func (Config) WithResourceAttributes ¶
WithResourceAttributes adiciona múltiplos atributos ao resource.
func (Config) WithServiceVersion ¶
WithServiceVersion define a versão do serviço. Se não fornecido, será lido de GRAFTEL_SERVICE_VERSION.
type ContextLogger ¶
type ContextLogger struct {
// contains filtered or unexported fields
}
func NewContextLogger ¶
func NewContextLogger(logger LogsHelper, ctx context.Context) *ContextLogger
func (*ContextLogger) Debug ¶
func (cl *ContextLogger) Debug(msg string, tags ...attribute.KeyValue)
func (*ContextLogger) Error ¶
func (cl *ContextLogger) Error(msg string, tags ...attribute.KeyValue)
func (*ContextLogger) ErrorWithError ¶
func (cl *ContextLogger) ErrorWithError(msg string, err error, tags ...attribute.KeyValue)
func (*ContextLogger) Fatal ¶
func (cl *ContextLogger) Fatal(msg string, tags ...attribute.KeyValue)
func (*ContextLogger) Log ¶
func (cl *ContextLogger) Log(level LogLevel, msg string, tags ...attribute.KeyValue)
func (*ContextLogger) LogWithError ¶
func (*ContextLogger) LogWithFields ¶
func (*ContextLogger) Trace ¶
func (cl *ContextLogger) Trace(msg string, tags ...attribute.KeyValue)
func (*ContextLogger) WithTags ¶
func (cl *ContextLogger) WithTags(tags ...attribute.KeyValue) *ContextLogger
type Counter ¶
type Counter struct {
// contains filtered or unexported fields
}
Counter representa um contador de métricas. Use NewCounter para criar uma instância.
type ErrInitializationFailed ¶
ErrInitializationFailed é retornado quando a inicialização falha.
func (*ErrInitializationFailed) Error ¶
func (e *ErrInitializationFailed) Error() string
func (*ErrInitializationFailed) Unwrap ¶
func (e *ErrInitializationFailed) Unwrap() error
type ErrInvalidConfig ¶
ErrInvalidConfig é retornado quando a configuração é inválida.
func (*ErrInvalidConfig) Error ¶
func (e *ErrInvalidConfig) Error() string
type ErrShutdownFailed ¶
ErrShutdownFailed é retornado quando o shutdown falha.
func (*ErrShutdownFailed) Error ¶
func (e *ErrShutdownFailed) Error() string
func (*ErrShutdownFailed) Unwrap ¶
func (e *ErrShutdownFailed) Unwrap() error
type Gauge ¶
type Gauge struct {
// contains filtered or unexported fields
}
Gauge representa um gauge de métricas observável.
type Histogram ¶
type Histogram struct {
// contains filtered or unexported fields
}
Histogram representa um histograma de métricas.
type LogLevel ¶
type LogLevel int
LogLevel representa o nível de log.
const ( // LogLevelTrace representa o nível de log trace. LogLevelTrace LogLevel = iota // LogLevelDebug representa o nível de log debug. LogLevelDebug // LogLevelInfo representa o nível de log info. LogLevelInfo // LogLevelWarn representa o nível de log warn. LogLevelWarn // LogLevelError representa o nível de log error. LogLevelError // LogLevelFatal representa o nível de log fatal. LogLevelFatal )
type LogsHelper ¶
type LogsHelper interface {
// Log envia um log com nível, mensagem e tags.
Log(ctx context.Context, level LogLevel, msg string, tags ...attribute.KeyValue)
// LogWithFields envia um log com campos extras formatados.
LogWithFields(ctx context.Context, level LogLevel, msg string, fields map[string]interface{}, tags ...attribute.KeyValue)
// LogWithError envia um log de erro com uma mensagem de erro.
LogWithError(ctx context.Context, level LogLevel, msg string, err error, tags ...attribute.KeyValue)
// Trace envia um log de nível trace.
Trace(ctx context.Context, msg string, tags ...attribute.KeyValue)
// Debug envia um log de nível debug.
Debug(ctx context.Context, msg string, tags ...attribute.KeyValue)
// Info envia um log de nível info.
Info(ctx context.Context, msg string, tags ...attribute.KeyValue)
// Warn envia um log de nível warn.
Warn(ctx context.Context, msg string, tags ...attribute.KeyValue)
// Error envia um log de nível error.
Error(ctx context.Context, msg string, tags ...attribute.KeyValue)
// Fatal envia um log de nível fatal.
Fatal(ctx context.Context, msg string, tags ...attribute.KeyValue)
// TraceWithFields envia um log trace com campos extras.
TraceWithFields(ctx context.Context, msg string, fields map[string]interface{}, tags ...attribute.KeyValue)
// DebugWithFields envia um log debug com campos extras.
DebugWithFields(ctx context.Context, msg string, fields map[string]interface{}, tags ...attribute.KeyValue)
// InfoWithFields envia um log info com campos extras.
InfoWithFields(ctx context.Context, msg string, fields map[string]interface{}, tags ...attribute.KeyValue)
// WarnWithFields envia um log warn com campos extras.
WarnWithFields(ctx context.Context, msg string, fields map[string]interface{}, tags ...attribute.KeyValue)
// ErrorWithFields envia um log error com campos extras.
ErrorWithFields(ctx context.Context, msg string, fields map[string]interface{}, tags ...attribute.KeyValue)
// FatalWithFields envia um log fatal com campos extras.
FatalWithFields(ctx context.Context, msg string, fields map[string]interface{}, tags ...attribute.KeyValue)
// ErrorWithError envia um log de erro com uma mensagem de erro.
ErrorWithError(ctx context.Context, msg string, err error, tags ...attribute.KeyValue)
}
LogsHelper facilita a criação e uso de logs estruturados. Use NewLogsHelper para criar uma instância.
func NewLogsHelper ¶
func NewLogsHelper(logger otellog.Logger) LogsHelper
NewLogsHelper cria um novo helper de logs.
type MetricsHelper ¶
type MetricsHelper interface {
// NewCounter cria um novo contador de métricas.
NewCounter(name, description string, opts ...otelmetric.Int64CounterOption) (*Counter, error)
// NewUpDownCounter cria um novo contador que pode incrementar ou decrementar.
NewUpDownCounter(name, description string, opts ...otelmetric.Int64UpDownCounterOption) (*UpDownCounter, error)
// NewHistogram cria um novo histograma de métricas.
NewHistogram(name, description string, opts ...otelmetric.Float64HistogramOption) (*Histogram, error)
// NewGauge cria um novo gauge observável.
NewGauge(name, description string, callback func(context.Context, otelmetric.Float64Observer) error, opts ...otelmetric.Float64ObservableGaugeOption) (*Gauge, error)
}
MetricsHelper facilita a criação e uso de métricas. Use NewMetricsHelper para criar uma instância.
func NewMetricsHelper ¶
func NewMetricsHelper(meter otelmetric.Meter) MetricsHelper
NewMetricsHelper cria um novo helper de métricas.
type MiddlewareConfig ¶
type MiddlewareConfig struct {
ServiceName string
SkipPaths []string
RecordRequestBody bool
RecordResponseBody bool
MaxBodySize int64
}
func DefaultMiddlewareConfig ¶
func DefaultMiddlewareConfig(serviceName string) MiddlewareConfig
type TracingHelper ¶
type TracingHelper interface {
StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
StartSpanWithTags(ctx context.Context, name string, tags ...attribute.KeyValue) (context.Context, trace.Span)
WithSpan(ctx context.Context, name string, fn func(context.Context) error, tags ...attribute.KeyValue) error
WithSpanAndReturn(ctx context.Context, name string, fn func(context.Context) (interface{}, error), tags ...attribute.KeyValue) (interface{}, error)
AddSpanTags(ctx context.Context, tags ...attribute.KeyValue)
SetSpanError(ctx context.Context, err error, tags ...attribute.KeyValue)
SetSpanStatus(ctx context.Context, code codes.Code, description string)
GetSpan(ctx context.Context) trace.Span
GetTraceID(ctx context.Context) string
GetSpanID(ctx context.Context) string
}
func NewTracingHelper ¶
func NewTracingHelper(tracer trace.Tracer) TracingHelper
type UpDownCounter ¶
type UpDownCounter struct {
// contains filtered or unexported fields
}
UpDownCounter representa um contador que pode incrementar ou decrementar.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
|
|
|
context
command
|
|
|
grafana-cloud
command
|
|
|
middleware
command
|
|
|
prometheus
command
|
|
|
tracing
command
|