arcotel

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 22 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

arco-otel-go

OpenTelemetry for Go apps on Arco Cloud, in a few lines.

arcotel is plain OpenTelemetry setup with sensible defaults. It exports OTLP/HTTP to OTEL_EXPORTER_OTLP_ENDPOINT and does nothing outside Arco Cloud tracing: when that variable is unset (your laptop, Docker, an environment with tracing off) Setup is a no-op and your app runs exactly as it would without it.

go get github.com/multi-api/arco-otel-go

Requires Go 1.26 or later.

Usage

import arcotel "github.com/multi-api/arco-otel-go"

shutdown := arcotel.Setup(ctx)               // no-op without OTEL_EXPORTER_OTLP_ENDPOINT
defer shutdown(context.Background())

db, err := arcotel.OpenDB("pgx", dsn)         // *sql.DB whose queries are spans (no parameter values)
client := &http.Client{Transport: arcotel.Transport(nil)}
arcotel.AWS(&awsCfg)                          // AWS SDK v2 calls
http.ListenAndServe("127.0.0.1:"+os.Getenv("PORT"), arcotel.Handler(mux))

A complete program is in example/main.go.

Function What it does
Setup(ctx) Tracer provider with an OTLP/HTTP exporter, a batch processor, Sampler(), Propagator() plus the baggage propagator, and service.name from OTEL_SERVICE_NAME. Returns the shutdown function.
Handler(h) Server spans for every request (otelhttp), named after the Go 1.22+ http.ServeMux pattern (GET /orders/{id}, with http.route). Also answers the platform's flush endpoint (below).
Route(r, pattern) Sets http.route and the span name from another router's matched route.
OpenDB(driver, dsn, opts...) / WrapDB(connector, opts...) A database/sql wrapper (otelsql). The SQL text is recorded; parameter values never are. db.system comes from the driver (below).
Transport(base) Client spans for outgoing HTTP calls, and trace-context propagation to the service you call.
AWS(&cfg) Spans for AWS SDK for Go v2 calls (otelaws). Call it before creating clients.
Sampler() The sampler Arco Cloud expects; see Already using OpenTelemetry?.
Propagator() W3C trace context that keeps a deferred trace deferred on outgoing calls; see the same section.
Databases

Query spans carry db.system (postgresql, mysql, sqlite, mssql), which groups them per database in the service map. OpenDB takes it from the driver name (pgx, postgres, mysql, sqlite3, ...); WrapDB takes it from the connector's driver package (pgx, lib/pq, go-sql-driver/mysql, the common SQLite and SQL Server drivers). For any other driver, pass it yourself:

db := arcotel.WrapDB(connector, arcotel.WithDBSystem("postgresql"))

WithDBSystem also overrides the inferred value.

Exporting to a local agent

When OTEL_EXPORTER_OTLP_ENDPOINT is a loopback address (127.0.0.1, localhost, ::1), as on Arco Cloud, exports are not retried and time out after one second, so a missing or stuck agent never delays your app or its shutdown. Spans of a failed export are dropped. Other endpoints keep the exporter's defaults.

The standard OTEL_* environment variables (OTEL_EXPORTER_OTLP_*, OTEL_RESOURCE_ATTRIBUTES, OTEL_BSP_*, …) work as usual. Arco Cloud sets the ones it needs when tracing is on.

The flush endpoint

Handler answers POST /_arco/otel/flush itself: it flushes the tracer provider and replies 204 No Content once every span ended before the call has been exported. The platform calls it after each response, so traces are complete without slowing your responses down. Your handler never sees this path (other methods get 405), and the platform does not expose it publicly.

Frameworks

Wrap the router with arcotel.Handler and report the matched route with arcotel.Route.

http.ServeMux behind middleware. Handler reads the matched pattern from r.Pattern, which ServeMux sets on the request it was given. A middleware between Handler and the mux that replaces the request (r.WithContext(...), r.Clone(...)) hides it, and spans fall back to the method alone. In that case call arcotel.Route(r, r.Pattern) inside the mux's handlers, or put the middleware outside Handler:

mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
    arcotel.Route(r, r.Pattern)
    // ...
})

chi

r := chi.NewRouter()
r.Use(func(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        next.ServeHTTP(w, req)
        arcotel.Route(req, chi.RouteContext(req.Context()).RoutePattern())
    })
})
http.ListenAndServe(addr, arcotel.Handler(r))

Gin

r := gin.New()
r.Use(func(c *gin.Context) {
    c.Next()
    arcotel.Route(c.Request, c.FullPath())
})
http.ListenAndServe(addr, arcotel.Handler(r))

If you already use otelgin, you can keep it; arcotel.Handler then adds an outer server span around the otelgin one.

Echo

e := echo.New()
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
    return func(c echo.Context) error {
        err := next(c)
        arcotel.Route(c.Request(), c.Path())
        return err
    }
})
http.ListenAndServe(addr, arcotel.Handler(e))

The same note applies to otelecho.

Fiber (fasthttp, not net/http): use otelfiber for request spans, and mount the flush endpoint before the middleware so it does not create spans of its own:

app := fiber.New()
app.Post("/_arco/otel/flush", adaptor.HTTPHandler(arcotel.Handler(http.NotFoundHandler())))
app.Use(otelfiber.Middleware())

Already using OpenTelemetry?

Keep your setup and change three things:

  1. Use the Arco sampler. Arco Cloud starts each trace and may defer the keep-or-drop decision until the request ends (traceparent …-00 with tracestate: arco=d); the stock ParentBased sampler records nothing in that case, so your app would only get its root spans.

  2. Use the Arco propagator. Spans of a deferred trace are recorded as sampled so they can be exported; the stock TraceContext propagator would then send -01 to the services you call. arcotel.Propagator() sends -00 with arco=d instead, so the decision stays deferred downstream. Extraction is unchanged.

    tp := sdktrace.NewTracerProvider(
        sdktrace.WithSampler(arcotel.Sampler()),
        sdktrace.WithBatcher(exporter),
    )
    otel.SetTracerProvider(tp)
    otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
        arcotel.Propagator(), propagation.Baggage{},
    ))
    
  3. Export OTLP to OTEL_EXPORTER_OTLP_ENDPOINT (the default for the OTLP exporters).

arcotel.Sampler() and arcotel.Propagator() have no other dependency on this module's setup. For complete traces, also wrap your handler with arcotel.Handler (it flushes your global provider on the flush endpoint), or keep the batch timeout short, for example OTEL_BSP_SCHEDULE_DELAY=20.

Development

go test -race ./... && go vet ./...

License

MIT, see LICENSE.

Documentation

Overview

Package arcotel is a small OpenTelemetry setup for Go apps on Arco Cloud.

It is plain OpenTelemetry with a few defaults: it exports OTLP/HTTP to OTEL_EXPORTER_OTLP_ENDPOINT and does nothing at all when that variable is unset (your laptop, Docker, an environment without tracing).

shutdown := arcotel.Setup(ctx)
defer shutdown(context.Background())
http.ListenAndServe(addr, arcotel.Handler(mux))

Index

Constants

View Source
const FlushPath = "/_arco/otel/flush"

FlushPath is the endpoint Handler answers itself: a POST there flushes the tracer provider and returns 204 once every span ended before it has been exported. The platform calls it after each response; your handler never sees this path.

Variables

This section is empty.

Functions

func AWS

func AWS(cfg *aws.Config)

AWS instruments an AWS SDK for Go v2 config: every call made by clients built from cfg afterwards is a span, and trace context is injected with the global propagator (Propagator() once Setup has run). Call it once, before creating clients.

cfg, _ := config.LoadDefaultConfig(ctx)
arcotel.AWS(&cfg)
s3Client := s3.NewFromConfig(cfg)

func Handler

func Handler(h http.Handler) http.Handler

Handler wraps h with OpenTelemetry server instrumentation (otelhttp) and the flush endpoint (FlushPath). With Go 1.22+ http.ServeMux patterns the route is recorded automatically; with other routers call Route.

func OpenDB

func OpenDB(driverName, dsn string, opts ...DBOption) (*sql.DB, error)

OpenDB opens a *sql.DB whose queries become spans, like sql.Open(driverName, dsn). The SQL text is recorded (db.statement / db.query.text); parameter values never are. Import the driver as usual, for example _ "github.com/jackc/pgx/v5/stdlib" for driverName "pgx". db.system comes from the driver name, or from WithDBSystem.

func Propagator

func Propagator() propagation.TextMapPropagator

Propagator returns the W3C trace-context propagator Arco Cloud expects. It behaves like propagation.TraceContext, except that a span whose tracestate carries arco=d (keep-or-drop decision deferred) is injected with the sampled flag cleared: traceparent ends in -00 and tracestate keeps arco=d, so the services the app calls see the trace as still deferred. Extract is unchanged.

Setup installs it (with the baggage propagator). Apps that configure OpenTelemetry themselves should install it next to Sampler():

otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
	arcotel.Propagator(), propagation.Baggage{}))

func Route

func Route(r *http.Request, pattern string)

Route sets http.route (and the span name "METHOD route") on the server span of r. Use it with routers other than http.ServeMux, for example with chi's matched route pattern. A ServeMux-style pattern such as "GET /orders/{id}" is accepted; its method and host are stripped. It does nothing outside a traced request.

func Sampler

func Sampler() sdktrace.Sampler

Sampler returns the sampler Arco Cloud expects. It is parent-based:

  • a parent with the sampled flag (-01) is recorded and sampled;
  • an unsampled parent (-00) whose tracestate carries arco=d (the decision is deferred until the request ends) is recorded and sampled (so it can be exported), and the tracestate is kept; Propagator() then sends -00 with arco=d on outgoing calls, so the decision stays deferred downstream;
  • any other unsampled parent (a bare -00) is dropped;
  • a span without a parent is sampled.

Apps that configure OpenTelemetry themselves can use it on its own:

sdktrace.NewTracerProvider(sdktrace.WithSampler(arcotel.Sampler()), ...)

A stock ParentBased sampler records nothing under a -00 parent, so without this sampler such an app only gets the spans created outside the request.

func Setup

func Setup(ctx context.Context) func(context.Context) error

Setup installs a global tracer provider that exports OTLP/HTTP to OTEL_EXPORTER_OTLP_ENDPOINT through a batch processor, using Sampler(), and installs Propagator() (W3C trace context) with the baggage propagator. The service name comes from OTEL_SERVICE_NAME; the other standard OTEL_* variables are honoured.

Without OTEL_EXPORTER_OTLP_ENDPOINT it does nothing: the global provider is left alone and the returned shutdown is a no-op. Setup never fails the app: if the exporter cannot be built, the error goes to the OpenTelemetry error handler and Setup behaves as a no-op.

Call the returned function before the process exits to flush pending spans.

func Transport

func Transport(base http.RoundTripper) http.RoundTripper

Transport wraps base (http.DefaultTransport when nil) so every outgoing request is a client span and carries the trace context to the next service, using the global propagator (Propagator() once Setup has run).

client := &http.Client{Transport: arcotel.Transport(nil)}

func WrapDB

func WrapDB(c driver.Connector, opts ...DBOption) *sql.DB

WrapDB is OpenDB for a driver.Connector, like sql.OpenDB(c). db.system comes from the connector's driver package (pgx, lib/pq, go-sql-driver/mysql, the common SQLite and SQL Server drivers), or from WithDBSystem.

Types

type DBOption

type DBOption func(*dbConfig)

DBOption configures OpenDB and WrapDB.

func WithDBSystem

func WithDBSystem(system string) DBOption

WithDBSystem sets the db.system attribute of the query spans (for example "postgresql", "mysql" or "sqlite"), for a driver that OpenDB or WrapDB does not recognise. The service map groups queries by it.

Directories

Path Synopsis
Command example is a minimal net/http app instrumented with arcotel.
Command example is a minimal net/http app instrumented with arcotel.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址