Documentation
¶
Index ¶
- func Attrs(attrs ...attr.Attr) commonOption
- func Debug(ctx context.Context, msg string, attrs ...attr.Attr)
- func Do(ctx context.Context, req *http.Request) (*http.Response, error)
- func Error(ctx context.Context, msg string, attrs ...attr.Attr)
- func Failure(err error) operationOnlyOption
- func Get(ctx context.Context, url string) (*http.Response, error)
- func HTTPMiddleware(ctx context.Context, handler http.Handler, opts ...MiddlewareOption) http.Handler
- func Info(ctx context.Context, msg string, attrs ...attr.Attr)
- func Init(ctx context.Context, opts ...InitOption) (context.Context, func())
- func Log(ctx context.Context, level slog.Level, msg string, attrs ...attr.Attr)
- func MetricLabels(labelNames ...string) operationOnlyOption
- func NewClient(base *http.Client) *http.Client
- func NoTrace() commonOption
- func Post(ctx context.Context, url, contentType string, body io.Reader) (*http.Response, error)
- func Success() operationOnlyOption
- func Warn(ctx context.Context, msg string, attrs ...attr.Attr)
- func WithBedrock(ctx context.Context, b *Bedrock) context.Context
- func WithRemoteParent(parent trace.SpanContext) operationOnlyOption
- type Bedrock
- type CloudOption
- type Config
- type CounterWithStatic
- type EndOption
- type GaugeWithStatic
- type HistogramWithStatic
- type InitOption
- type MiddlewareOption
- func WithAdditionalAttrs(fn func(*http.Request) []attr.Attr) MiddlewareOption
- func WithAdditionalLabels(labels ...string) MiddlewareOption
- func WithOperationName(name string) MiddlewareOption
- func WithSuccessCodes(codes ...int) MiddlewareOption
- func WithTracePropagation(enable bool) MiddlewareOption
- type Op
- type OpStep
- type OperationOption
- type ProfileType
- type SourceOption
- type Src
- type StepOption
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Attrs ¶
Attrs adds attributes to an operation or step. For operations, these can be used to populate metric labels if the label was registered.
func Debug ¶
Debug logs a debug message with the given attributes. Uses the bedrock logger from context, which includes static attributes.
Usage:
bedrock.Debug(ctx, "processing request", attr.String("user_id", "123"))
func Do ¶ added in v0.2.0
Do executes an HTTP request with bedrock instrumentation. This is a convenience function that creates a one-time instrumented client.
For better performance with multiple requests, create a client once with NewClient and reuse it.
Usage:
req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.example.com/users", nil) resp, err := bedrock.Do(ctx, req)
func Error ¶
Error logs an error message with the given attributes. Uses the bedrock logger from context, which includes static attributes.
Usage:
bedrock.Error(ctx, "database connection failed", attr.Error(err))
func Failure ¶
func Failure(err error) operationOnlyOption
Failure marks the operation as failed with an error.
func Get ¶ added in v0.2.0
Get is a convenience function for GET requests with bedrock instrumentation.
Usage:
resp, err := bedrock.Get(ctx, "https://api.example.com/users")
func HTTPMiddleware ¶
func HTTPMiddleware(ctx context.Context, handler http.Handler, opts ...MiddlewareOption) http.Handler
HTTPMiddleware wraps an HTTP handler with bedrock operations. It expects bedrock to already be in the context (use Init or WithBedrock first).
Usage:
ctx, close := bedrock.Init(ctx)
defer close()
mux := http.NewServeMux()
mux.HandleFunc("/users", handleUsers)
handler := bedrock.HTTPMiddleware(ctx, mux)
http.ListenAndServe(":8080", handler)
func Info ¶
Info logs an info message with the given attributes. Uses the bedrock logger from context, which includes static attributes.
Usage:
bedrock.Info(ctx, "request completed", attr.Int("status", 200))
func Init ¶
func Init(ctx context.Context, opts ...InitOption) (context.Context, func())
Init initializes bedrock in the context and returns a context with bedrock attached and a cleanup function. If no config is provided, it loads from environment variables.
The observability server is automatically started if Config.ServerEnabled is true. Set ServerEnabled to true in your config to enable automatic server startup.
Usage:
ctx, close := bedrock.Init(ctx, bedrock.WithConfig(cfg)) defer close()
func Log ¶
Log logs a message at the given level with attributes. Uses the bedrock logger from context, which includes static attributes.
Usage:
bedrock.Log(ctx, slog.LevelInfo, "custom log", attr.String("key", "value"))
func MetricLabels ¶
func MetricLabels(labelNames ...string) operationOnlyOption
MetricLabels defines the label names for this operation's metrics upfront. If a label is defined but no attribute with that key is set, the value will be "_". This prevents unlimited cardinality by pre-defining all possible label dimensions.
func NewClient ¶ added in v0.2.0
NewClient creates an http.Client with bedrock instrumentation. The client automatically injects trace context and creates spans for requests. The tracer is obtained from the context when requests are made.
Usage:
client := bedrock.NewClient(nil) // Uses default HTTP client settings
resp, err := client.Get("https://api.example.com/users")
Or with custom settings:
base := &http.Client{Timeout: 30 * time.Second}
client := bedrock.NewClient(base)
func NoTrace ¶ added in v0.3.1
func NoTrace() commonOption
NoTrace disables tracing for this operation/step and all children. Use this for hot code paths where trace telemetry would cause too much noise. Metrics will still be recorded for operations.
func Post ¶ added in v0.2.0
Post is a convenience function for POST requests with bedrock instrumentation.
Usage:
body := strings.NewReader(`{"name": "John"}`)
resp, err := bedrock.Post(ctx, "https://api.example.com/users", "application/json", body)
func Success ¶
func Success() operationOnlyOption
Success marks the operation as successful (affects auto-generated success/failure metrics).
func Warn ¶
Warn logs a warning message with the given attributes. Uses the bedrock logger from context, which includes static attributes.
Usage:
bedrock.Warn(ctx, "high latency detected", attr.Duration("latency", 5*time.Second))
func WithBedrock ¶
WithBedrock returns a context with the bedrock instance attached. This is the primary way to propagate bedrock through your application.
func WithRemoteParent ¶ added in v0.2.0
func WithRemoteParent(parent trace.SpanContext) operationOnlyOption
WithRemoteParent sets the remote parent from W3C Trace Context headers.
Types ¶
type Bedrock ¶
type Bedrock struct {
// contains filtered or unexported fields
}
Bedrock is the main entry point for observability.
func FromContext ¶
FromContext returns the bedrock instance from the context. Returns nil if no bedrock instance exists (use this for optional access).
func (*Bedrock) MetricsRegistry ¶ added in v0.4.0
MetricsRegistry returns the metric registry (alias for Metrics).
type CloudOption ¶ added in v0.4.0
type CloudOption func(*cloudConfig)
CloudOption configures the cloud backend connection.
func CloudEndpoint ¶ added in v0.4.0
func CloudEndpoint(url string) CloudOption
CloudEndpoint overrides the default ingest URL (https://ingest.bedrock.dev).
func CloudInsecure ¶ added in v0.4.0
func CloudInsecure() CloudOption
CloudInsecure disables TLS for the gRPC trace connection. Intended for local development against a local OTLP collector.
func CloudProfileCPUSampleDuration ¶ added in v0.4.0
func CloudProfileCPUSampleDuration(d time.Duration) CloudOption
CloudProfileCPUSampleDuration sets how long the CPU profiler collects samples within each profiling interval (default 10s).
func CloudProfileInterval ¶ added in v0.4.0
func CloudProfileInterval(d time.Duration) CloudOption
CloudProfileInterval sets the interval between continuous profiling snapshots (default 60s).
func CloudPushInterval ¶ added in v0.4.0
func CloudPushInterval(d time.Duration) CloudOption
CloudPushInterval sets the interval at which Prometheus metrics are pushed to the managed platform (default 15s).
type Config ¶
type Config struct {
// Service is the name of the service.
Service string `env:"BEDROCK_SERVICE" envDefault:"unknown"`
// Tracing configuration
//
// TraceURL is the OTLP trace endpoint.
// Format depends on TraceProtocol:
// gRPC → "host:port" (e.g. "localhost:4317")
// HTTP → full URL (e.g. "http://localhost:4318/v1/traces")
//
// When TraceProtocol is empty the protocol is auto-detected:
// • URL with scheme (http:// / https://) or containing "/" → HTTP/JSON
// • Plain "host:port" without scheme/path → gRPC (default)
TraceURL string `env:"BEDROCK_TRACE_URL"`
// TraceProtocol selects the OTLP export protocol: "grpc" or "http".
// Leave empty to auto-detect from TraceURL (see above).
TraceProtocol string `env:"BEDROCK_TRACE_PROTOCOL"`
// TraceInsecure disables TLS for gRPC transport (h2c cleartext).
// Ignored for HTTP transport.
TraceInsecure bool `env:"BEDROCK_TRACE_INSECURE" envDefault:"false"`
// TraceSampleRate controls trace sampling (0.0 to 1.0).
TraceSampleRate float64 `env:"BEDROCK_TRACE_SAMPLE_RATE" envDefault:"1.0"`
// TraceSampler controls trace sampling (overrides TraceSampleRate if set).
TraceSampler trace.Sampler `env:"-"`
// Logging configuration
// LogLevel is the minimum log level (DEBUG, INFO, WARN, ERROR).
LogLevel string `env:"BEDROCK_LOG_LEVEL" envDefault:"INFO"`
// LogFormat is "json" or "text".
LogFormat string `env:"BEDROCK_LOG_FORMAT" envDefault:"json"`
// LogOutput is the log output writer. Defaults to os.Stderr.
LogOutput io.Writer `env:"-"`
// LogAddSource adds source code position to log output.
LogAddSource bool `env:"BEDROCK_LOG_ADD_SOURCE" envDefault:"true"`
// LogCanonical enables structured logging of operation completion.
LogCanonical bool `env:"BEDROCK_LOG_CANONICAL" envDefault:"false"`
// Metrics configuration
// MetricPrefix is prepended to all metric names.
MetricPrefix string `env:"BEDROCK_METRIC_PREFIX"`
// MetricBuckets are the default histogram buckets.
MetricBuckets []float64 `env:"BEDROCK_METRIC_BUCKETS"`
// RuntimeMetrics enables automatic collection of Go runtime metrics.
RuntimeMetrics bool `env:"BEDROCK_RUNTIME_METRICS" envDefault:"true"`
// Server configuration
// ServerEnabled enables the automatic observability server.
ServerEnabled bool `env:"BEDROCK_SERVER_ENABLED" envDefault:"true"`
// ServerAddr is the address to listen on.
ServerAddr string `env:"BEDROCK_SERVER_ADDR" envDefault:":9090"`
// ServerMetrics enables /metrics endpoint.
ServerMetrics bool `env:"BEDROCK_SERVER_METRICS" envDefault:"true"`
// ServerPprof enables /debug/pprof endpoints.
ServerPprof bool `env:"BEDROCK_SERVER_PPROF" envDefault:"true"`
// ServerReadTimeout is the max request read duration.
ServerReadTimeout time.Duration `env:"BEDROCK_SERVER_READ_TIMEOUT" envDefault:"10s"`
// ServerReadHeaderTimeout is the header read timeout.
ServerReadHeaderTimeout time.Duration `env:"BEDROCK_SERVER_READ_HEADER_TIMEOUT" envDefault:"5s"`
// ServerWriteTimeout is the response write timeout.
ServerWriteTimeout time.Duration `env:"BEDROCK_SERVER_WRITE_TIMEOUT" envDefault:"30s"`
// ServerIdleTimeout is the keep-alive timeout.
ServerIdleTimeout time.Duration `env:"BEDROCK_SERVER_IDLE_TIMEOUT" envDefault:"120s"`
// ServerMaxHeaderBytes is the header size limit.
ServerMaxHeaderBytes int `env:"BEDROCK_SERVER_MAX_HEADER_BYTES" envDefault:"1048576"` // 1 MB
// ShutdownTimeout is the timeout for shutdown operations.
ShutdownTimeout time.Duration `env:"BEDROCK_SHUTDOWN_TIMEOUT" envDefault:"30s"`
}
Config configures the Bedrock instance.
func MustFromEnv ¶
func MustFromEnv() Config
MustFromEnv loads configuration from environment variables, panicking on error.
type CounterWithStatic ¶
type CounterWithStatic struct {
// contains filtered or unexported fields
}
CounterWithStatic wraps a metric.Counter and automatically includes static labels.
func Counter ¶
func Counter(ctx context.Context, name, help string, labelNames ...string) *CounterWithStatic
Counter creates or retrieves a counter metric from the bedrock instance in context. Static labels are automatically included when recording values.
Usage:
counter := bedrock.Counter(ctx, "http_requests_total", "Total HTTP requests", "method", "status")
counter.With(attr.String("method", "GET"), attr.String("status", "200")).Inc()
// Or without additional labels:
counter.Inc() // automatically includes static labels
func (*CounterWithStatic) Add ¶
func (c *CounterWithStatic) Add(v float64)
Add adds the given value to the counter with static labels.
func (*CounterWithStatic) Inc ¶
func (c *CounterWithStatic) Inc()
Inc increments the counter by 1 with static labels.
func (*CounterWithStatic) With ¶
func (c *CounterWithStatic) With(labels ...attr.Attr) metric.CounterVec
With returns a CounterVec with the given label values plus static labels.
type EndOption ¶
type EndOption func(*endConfig)
EndOption configures how an operation ends.
func EndFailure ¶
EndFailure marks the operation as failed when ending.
func EndSuccess ¶
func EndSuccess() EndOption
EndSuccess marks the operation as successful when ending.
type GaugeWithStatic ¶
type GaugeWithStatic struct {
// contains filtered or unexported fields
}
GaugeWithStatic wraps a metric.Gauge and automatically includes static labels.
func Gauge ¶
func Gauge(ctx context.Context, name, help string, labelNames ...string) *GaugeWithStatic
Gauge creates or retrieves a gauge metric from the bedrock instance in context. Static labels are automatically included when recording values.
Usage:
gauge := bedrock.Gauge(ctx, "active_connections", "Active connections") gauge.Set(42) // automatically includes static labels
func (*GaugeWithStatic) Add ¶
func (g *GaugeWithStatic) Add(v float64)
Add adds the given value to the gauge with static labels.
func (*GaugeWithStatic) Dec ¶
func (g *GaugeWithStatic) Dec()
Dec decrements the gauge by 1 with static labels.
func (*GaugeWithStatic) Inc ¶
func (g *GaugeWithStatic) Inc()
Inc increments the gauge by 1 with static labels.
func (*GaugeWithStatic) Set ¶
func (g *GaugeWithStatic) Set(v float64)
Set sets the gauge to the given value with static labels.
func (*GaugeWithStatic) Sub ¶
func (g *GaugeWithStatic) Sub(v float64)
Sub subtracts the given value from the gauge with static labels.
type HistogramWithStatic ¶
type HistogramWithStatic struct {
// contains filtered or unexported fields
}
HistogramWithStatic wraps a metric.Histogram and automatically includes static labels.
func Histogram ¶
func Histogram(ctx context.Context, name, help string, buckets []float64, labelNames ...string) *HistogramWithStatic
Histogram creates or retrieves a histogram metric from the bedrock instance in context. Uses default buckets if buckets is nil. Static labels are automatically included when recording values.
Usage:
hist := bedrock.Histogram(ctx, "request_duration_ms", "Request duration", nil, "method")
hist.With(attr.String("method", "GET")).Observe(123.45)
// Or without additional labels:
hist.Observe(123.45) // automatically includes static labels
func (*HistogramWithStatic) Observe ¶
func (h *HistogramWithStatic) Observe(v float64)
Observe records an observation with static labels.
func (*HistogramWithStatic) With ¶
func (h *HistogramWithStatic) With(labels ...attr.Attr) metric.HistogramVec
With returns a HistogramVec with the given label values plus static labels.
type InitOption ¶
type InitOption func(*initConfig)
InitOption configures initialization.
func WithCloud ¶ added in v0.4.0
func WithCloud(apiKey string, opts ...CloudOption) InitOption
WithCloud configures the SDK to export telemetry to the Bedrock managed platform. The apiKey is sent as an x-bedrock-key gRPC metadata header for traces and as an Authorization: Bearer header for metrics and profiles.
When WithCloud is combined with a local BEDROCK_TRACE_URL, spans are exported to both destinations via a fan-out exporter.
Usage:
ctx, close := bedrock.Init(context.Background(),
bedrock.WithCloud("brk_live_abc123"),
)
defer close()
func WithConfig ¶
func WithConfig(cfg Config) InitOption
WithConfig provides an explicit configuration.
func WithLogLevel ¶ added in v0.2.1
func WithLogLevel(level string) InitOption
WithLogLevel sets the log level for the bedrock instance. Valid levels: "debug", "info", "warn", "error" This is a convenience wrapper that modifies the config.
Usage:
ctx, close := bedrock.Init(ctx, bedrock.WithLogLevel("debug"))
func WithStaticAttrs ¶
func WithStaticAttrs(attrs ...attr.Attr) InitOption
WithStaticAttrs sets static attributes for all operations.
type MiddlewareOption ¶
type MiddlewareOption func(*middlewareConfig)
MiddlewareOption configures the HTTP middleware.
func WithAdditionalAttrs ¶
func WithAdditionalAttrs(fn func(*http.Request) []attr.Attr) MiddlewareOption
WithAdditionalAttrs provides a function to extract additional attributes from the request.
func WithAdditionalLabels ¶
func WithAdditionalLabels(labels ...string) MiddlewareOption
WithAdditionalLabels adds extra metric label names beyond the defaults. Default labels are: method, path, status_code
func WithOperationName ¶
func WithOperationName(name string) MiddlewareOption
WithOperationName sets a custom operation name (default: "http.request").
func WithSuccessCodes ¶
func WithSuccessCodes(codes ...int) MiddlewareOption
WithSuccessCodes defines which HTTP status codes are considered successful. Default: 2xx and 3xx are success, 4xx and 5xx are failures.
func WithTracePropagation ¶ added in v0.2.0
func WithTracePropagation(enable bool) MiddlewareOption
WithTracePropagation enables or disables W3C Trace Context propagation. Default: enabled (true).
type Op ¶
type Op struct {
// contains filtered or unexported fields
}
Op is a handle to an operation.
func Operation ¶
Operation starts a new operation and returns the operation handle and updated context. Success is the default state. Register errors via attr.Error() to mark as failure.
Accepts both common options (Attrs, NoTrace) and operation-specific options (MetricLabels, etc).
Usage:
op, ctx := bedrock.Operation(ctx, "process_user")
defer op.Done()
op, ctx := bedrock.Operation(ctx, "hot_path", bedrock.NoTrace())
op.Register(ctx, attr.String("user_id", "123"))
func (*Op) Done ¶
func (op *Op) Done()
Done completes the operation and records all automatic metrics.
func (*Op) Event ¶ added in v0.4.0
Event records a trace event on the operation span.
Usage:
op.Event(ctx, attr.NewEvent("cache.hit", attr.String("key", "user:123")))
func (*Op) Register ¶
Register adds attributes to the operation. Attributes can be used for metrics if they match registered metric label names. Use attr.Error(err) to register errors and mark the operation as failed.
Usage:
op.Register(ctx,
attr.String("user_id", "123"),
attr.Error(err), // marks as failure if err != nil
)
type OpStep ¶
type OpStep struct {
// contains filtered or unexported fields
}
OpStep is a handle to a step within an operation. Steps contribute their attributes to the parent operation.
func Step ¶
func Step(ctx context.Context, name string, opts ...StepOption) *OpStep
Step creates a lightweight step within an operation for tracing without full operation metrics. Steps are part of their parent operation and contribute attributes/events to it. Use this for helper functions where you want trace visibility but not separate metrics.
Accepts common options (Attrs, NoTrace).
Usage:
step := bedrock.Step(ctx, "helper")
defer step.Done()
step := bedrock.Step(ctx, "helper", bedrock.Attrs(attr.String("key", "value")))
step := bedrock.Step(ctx, "hot_path", bedrock.NoTrace())
func StepFromContext ¶
func StepFromContext(ctx context.Context, name string, opts ...StepOption) *OpStep
StepFromContext creates a lightweight step within an operation for tracing without full operation metrics. Steps are part of their parent operation and contribute attributes/events to it. Use this for helper functions where you want trace visibility but not separate metrics.
Usage:
step := bedrock.Step(ctx, "helper") defer step.Done()
func (*OpStep) Done ¶
func (s *OpStep) Done()
Done ends the step, syncing accumulated attrs to the span in one shot.
type OperationOption ¶
type OperationOption interface {
// contains filtered or unexported methods
}
OperationOption configures an operation.
type ProfileType ¶ added in v0.4.0
type ProfileType string
ProfileType identifies the kind of profile to collect.
const ( ProfileTypeCPU ProfileType = "cpu" ProfileTypeHeap ProfileType = "heap" ProfileTypeGoroutine ProfileType = "goroutine" ProfileTypeMutex ProfileType = "mutex" )
type SourceOption ¶
type SourceOption func(*sourceConfig)
SourceOption configures a source.
func SourceAttrs ¶
func SourceAttrs(attrs ...attr.Attr) SourceOption
SourceAttrs adds attributes to a source.
func SourceMetricLabels ¶
func SourceMetricLabels(labelNames ...string) SourceOption
SourceMetricLabels defines the label names for operations started from this source. All operations from this source will use these as their metric label names. If an operation doesn't provide a value for a label, it will be set to "_".
type Src ¶
type Src struct {
// contains filtered or unexported fields
}
Src is a handle to a source.
func Source ¶
Source registers a source in the context and returns the source handle. Sources are for long-running processes that spawn operations.
Usage:
source, ctx := bedrock.Source(ctx, "background.worker") defer source.Done() source.Sum(ctx, "loops", 1)
func (*Src) Done ¶
func (src *Src) Done()
Done signals the source is stopping. When LogCanonical is enabled it emits a structured completion log.
func (*Src) Gauge ¶ added in v0.4.0
Gauge sets a named gauge for the source to the given value.
Usage:
source.Gauge(ctx, "queue_depth", 42)
type StepOption ¶ added in v0.3.1
type StepOption interface {
// contains filtered or unexported methods
}
StepOption configures a step.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
h2c
Package h2c implements a minimal HTTP/2 cleartext (h2c prior knowledge) client sufficient for making gRPC unary RPC calls.
|
Package h2c implements a minimal HTTP/2 cleartext (h2c prior knowledge) client sufficient for making gRPC unary RPC calls. |
|
Package server provides an HTTP server for observability endpoints.
|
Package server provides an HTTP server for observability endpoints. |
|
http
Package http provides W3C Trace Context propagation for HTTP transports.
|
Package http provides W3C Trace Context propagation for HTTP transports. |
|
w3c
Package w3c provides utilities for parsing and formatting W3C Trace Context.
|
Package w3c provides utilities for parsing and formatting W3C Trace Context. |
|
Package transport provides HTTP transport instrumentation for bedrock.
|
Package transport provides HTTP transport instrumentation for bedrock. |