Documentation menu
SDKs

Go

Send logs, errors, metrics, heartbeats and deployments from Go, with a log/slog handler and net/http middleware.

The Go SDK needs Go 1.21 or newer. Its only dependency is go.opentelemetry.io/otel/trace. A Client is safe for concurrent use: logs and metrics are queued and sent by a background goroutine, and logging never returns an error.

Install

go get github.com/nad3rk/incidion/sdks/go
import incidion "github.com/nad3rk/incidion/sdks/go"

go get works once the tag sdks/go/v0.1.0 exists. Until then, check out the repository next to your module and point at the local copy:

// go.mod
require github.com/nad3rk/incidion/sdks/go v0.1.0

replace github.com/nad3rk/incidion/sdks/go => ../incidion/sdks/go

Quick start

package main

import (
	"context"
	"errors"
	"log"

	incidion "github.com/nad3rk/incidion/sdks/go"
)

func main() {
	client, err := incidion.New(incidion.Config{
		APIKey:  "pk_...", // or INCIDION_API_KEY
		Service: "checkout",
		Release: "1.4.0",
	})
	if err != nil {
		log.Fatal(err)
	}
	// Deliver what is still queued before the program exits (waits at most 5 s)
	defer client.Close(context.Background())

	ctx := context.Background()
	client.Info(ctx, "order placed",
		incidion.UserID("42"),
		incidion.Attr("order_id", "o-981"),
		incidion.Attr("amount_cents", 4200),
	)

	if err := charge(); err != nil {
		client.CaptureError(ctx, err, incidion.Attr("provider", "stripe"))
	}
}

func charge() error { return errors.New("card declined") }

Go has no exit hook, so call Close yourself. os.Exit and log.Fatal skip deferred calls.

Configuration

Every string field falls back to its environment variable when empty. Zero values mean the default.

Field Env var Default Description
APIKey INCIDION_API_KEY Public key pk_...: logs, metrics, heartbeats by monitor UUID
SecretKey INCIDION_SECRET_KEY APIKey if that is an sk_ key Secret key sk_...: deployments only; keep it in CI
ProjectID INCIDION_PROJECT_ID Needed for deployments
BaseURL INCIDION_BASE_URL https://ingest.incidion.dev Ingest host
APIURL INCIDION_API_URL derived API host for heartbeats and deployments, see below
Service INCIDION_SERVICE Default service of every log
EnvironmentID INCIDION_ENVIRONMENT_ID UUID of an Incidion environment, sent with every batch
Release INCIDION_RELEASE Added to every log’s attributes as release
FlushInterval 5 * time.Second Time between background sends
BatchSize 50 Most entries per request; reaching it sends at once
MaxQueueSize 10000 Entries waiting at most; the oldest are dropped beyond it
MaxRetries 5 Retries per batch; negative means none
MaxRetryDelay 300 * time.Second Longest wait before a retry, Retry-After included
BeforeSend func(*Entry) *Entry: change or drop (nil) a log
SampleRate 1 Fraction of logs below error that are kept; negative keeps none
Debug io.Writer for every SDK diagnostic, debug messages included
ErrorLog Debug, else os.Stderr io.Writer for SDK warnings and errors; io.Discard silences them
HTTPClient &http.Client{} For proxies or custom transports

APIURL defaults to https://api.incidion.dev for the default ingest, to https://staging.incidion.dev for https://ingest.staging.incidion.dev, and to BaseURL otherwise (self-hosted). A trailing /api/v1 is removed. Logs go to the environment of the key unless EnvironmentID is set.

Keys

At least one key is required; New returns ErrMissingAPIKey otherwise, and an error matching ErrInvalidEnvironmentID when EnvironmentID is set but not a UUID (the ingest would reject every batch). Services get the pk_ key; the sk_ key goes only into CI, for deployments. A client with only the secret key drops logs and metrics with one warning. An sk_ key in APIKey is used for deployments when SecretKey is empty, but New warns that logs need the pk_ key, and logs and metrics are dropped.

Logs

client.Log(ctx, incidion.LevelWarning, "disk almost full", incidion.Attr("free_gb", 3))
client.Debug(ctx, "cache miss", incidion.Attr("key", key))
client.Info(ctx, "user signed in", incidion.UserID(u.ID), incidion.SessionID(sid))
client.Warn(ctx, "slow query", incidion.Attr("ms", 812))
client.Error(ctx, "payment failed", incidion.Err(err))
client.Critical(ctx, "database unreachable")

Levels: LevelDebug, LevelInfo, LevelWarning, LevelError, LevelCritical. Fields fill the ingest’s columns:

Field Column(s)
Attr(k, v), Attrs(map) attributes (free-form)
Service, LoggerName service, logger
RequestID, TraceID, SpanID, UserID, SessionID same names
HTTPRequest(r) http_method, http_path, user_agent, ip_address (host of RemoteAddr), request_id (X-Request-ID)
HTTPMethod, HTTPPath, HTTPStatus, HTTPDuration http_method, http_path, http_status, http_duration_ms
IPAddress, UserAgent ip_address, user_agent
Err(err) error_type (the Go type, e.g. fs.PathError), error_message
StackTrace, Caller(file, line, fn) stack_trace, file_name / line_number / function_name
Time(t) timestamp (default: now)

Every log also carries hostname, pid, go_version and os in its attributes, plus sdk_name (incidion-go) and sdk_version.

Errors

if err := sync(ctx); err != nil {
	client.CaptureError(ctx, err, incidion.Attr("job", "sync"))
}

CaptureError logs at level error with error_type, error_message, the caller’s file, line and function, and a stack_trace of the goroutine at the call.

Context: tags, user, release, environment

client.SetTags(map[string]any{"region": "eu-west-1", "tenant": "acme"})
client.SetTag("feature_flag", "new-checkout")
client.SetTag("tenant", nil) // remove one
client.SetTags(nil)          // remove all
client.SetUser("42")         // user_id of every later log; "" clears it

Release and EnvironmentID are set in Config. Tags go into the attributes of every later log; an Attr with the same key wins over a tag, and a UserID field wins over SetUser. Tags apply to logs, not to metrics.

BeforeSend and sampling

var email = regexp.MustCompile(`[\w.+-]+@[\w-]+\.[\w.-]+`)

client, err := incidion.New(incidion.Config{
	APIKey: "pk_...",
	BeforeSend: func(e *incidion.Entry) *incidion.Entry {
		if e.HTTPPath == "/healthz" {
			return nil // drop
		}
		e.Message = email.ReplaceAllString(e.Message, "[email]")
		for k, v := range e.Attributes {
			if s, ok := v.(string); ok {
				e.Attributes[k] = email.ReplaceAllString(s, "[email]")
			}
		}
		return e
	},
	SampleRate: 0.1, // keep 10% of debug/info/warning; every error and critical
})

BeforeSend runs in the goroutine that logs, on the finished *incidion.Entry (its fields are the ingest’s columns). If it panics, the panic is reported once to ErrorLog and the entry is sent unchanged.

OpenTelemetry trace correlation

Every logging method takes a context.Context. When it carries an OpenTelemetry span and the log sets no TraceID or SpanID, the span’s ids (lowercase hex) fill trace_id and span_id.

ctx, span := tracer.Start(r.Context(), "checkout")
defer span.End()
client.Info(ctx, "charging card") // trace_id and span_id from the span

Incidion stores logs, not traces. To export logs with the OpenTelemetry Go SDK instead, see OpenTelemetry.

log/slog

logger := slog.New(incidion.NewSlogHandler(client, slog.LevelInfo))
slog.SetDefault(logger)

slog.Info("user signed in", "user_id", "42", slog.Group("auth", "method", "passkey"))
slog.ErrorContext(ctx, "charge failed", "error", err, "http_status", 402)
  • Levels: below Info is debug, Info info, Warn warning, Error error, and slog.LevelError+4 and above critical.
  • Attributes and groups become the log’s attributes; groups are nested objects ({"auth": {"method": "passkey"}}).
  • Ungrouped attributes named after a column (request_id, user_id, session_id, trace_id, span_id, http_method, http_path, http_status, http_duration_ms as a number or time.Duration, ip_address, user_agent, service, logger) fill that column.
  • An error value under error or err fills error_type and error_message.
  • The record’s caller fills file_name, line_number and function_name.
  • The context passed to InfoContext, ErrorContext and so on supplies the trace ids.

The SDK writes its own diagnostics to Debug and ErrorLog, never through slog or log, so installing the handler as the default cannot loop. To log to Incidion and to stdout, fan out to two handlers with a small multi-handler (or a package such as slog-multi).

net/http middleware

func withIncidion(client *incidion.Client, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(sw, r)

		level := incidion.LevelInfo
		if sw.status >= 500 {
			level = incidion.LevelError
		}
		client.Log(r.Context(), level, r.Method+" "+r.URL.Path,
			incidion.HTTPRequest(r), // method, path, user agent, ip, X-Request-ID
			incidion.HTTPStatus(sw.status),
			incidion.HTTPDuration(time.Since(start)),
		)
	})
}

type statusWriter struct {
	http.ResponseWriter
	status int
}

func (w *statusWriter) WriteHeader(code int) {
	w.status = code
	w.ResponseWriter.WriteHeader(code)
}

Behind a proxy, RemoteAddr is the proxy: pass incidion.IPAddress(...) after HTTPRequest(r) with the client address from your trusted header. With otelhttp.NewHandler around the handler, r.Context() carries the span and the trace ids are filled too.

Metrics

client.Metric(ctx, "queue.depth", 42, incidion.WithTags(map[string]string{"queue": "emails"}))
client.Metric(ctx, "request.duration", 12.5, incidion.WithUnit("ms"))
client.Metric(ctx, "cpu.usage", 63.1, incidion.WithUnit("percent"), incidion.WithHost("web-2"))

Metrics are queued with the logs and sent to /v1/metrics, one request per (host, tags) pair, with the same retries. The host defaults to the machine’s hostname. NaN and infinite values are dropped.

// A periodic reporter
go func() {
	var m runtime.MemStats
	for range time.Tick(30 * time.Second) {
		runtime.ReadMemStats(&m)
		client.Metric(ctx, "go.heap_alloc", float64(m.HeapAlloc), incidion.WithUnit("bytes"))
		client.Metric(ctx, "go.goroutines", float64(runtime.NumGoroutine()))
	}
}()

Heartbeats and cron jobs

Create a heartbeat monitor and copy its URL (or its hb_ token). Heartbeats need no API key.

// cmd/backup/main.go, run by cron: 0 3 * * * /opt/jobs/backup
func main() {
	client, err := incidion.New(incidion.Config{Service: "backup"}) // INCIDION_API_KEY
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	err = client.Job(ctx, os.Getenv("BACKUP_HEARTBEAT_URL"), func(ctx context.Context) error {
		return runBackup(ctx)
	}, incidion.JobSendStart())

	client.Close(ctx) // before os.Exit, which skips defers
	if err != nil {
		os.Exit(1)
	}
}

Job(ctx, monitor, fn, opts...) reports the start (with JobSendStart(), so Incidion records the run time), runs fn, then pings up, or down with the error message and logs the error with CaptureError (JobSkipCapture() turns that off). It returns fn’s error; a panic is reported as down and re-panicked. JobMessage("...") sets the message of the up ping.

Direct pings return an error when Incidion did not record them:

err := client.Heartbeat(ctx, "hb_x7...", incidion.HeartbeatUp, "processed 120 rows")
err = client.Heartbeat(ctx, "hb_x7...", incidion.HeartbeatDegraded, "queue backing up")
err = client.HeartbeatStart(ctx, "hb_x7...") // POST .../start/

monitor is the heartbeat URL, its hb_ token, or a monitor UUID (legacy, sent with the API key). Pings run in the caller’s goroutine with a 10 s timeout. More on monitors: Heartbeats.

Deployments from CI

Deployments need the project’s secret key (SecretKey / INCIDION_SECRET_KEY), ProjectID, and the Pro plan or higher. A small program run by your pipeline:

// tools/deploy/main.go: go run ./tools/deploy start | finish <id> <status>
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	incidion "github.com/nad3rk/incidion/sdks/go"
)

func main() {
	client, err := incidion.New(incidion.Config{}) // INCIDION_SECRET_KEY, INCIDION_PROJECT_ID
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close(context.Background())
	ctx := context.Background()
	repo := os.Getenv("GITHUB_SERVER_URL") + "/" + os.Getenv("GITHUB_REPOSITORY")

	switch os.Args[1] {
	case "start":
		id, err := client.DeploymentStart(ctx, incidion.DeploymentStart{
			Version:        os.Getenv("GITHUB_SHA")[:7],
			Environment:    "production", // the environment's slug in Incidion
			CommitHash:     os.Getenv("GITHUB_SHA"),
			Branch:         os.Getenv("GITHUB_REF_NAME"),
			RunURL:         repo + "/actions/runs/" + os.Getenv("GITHUB_RUN_ID"),
			RepositoryURL:  repo,
			DeployedByName: os.Getenv("GITHUB_ACTOR"),
		})
		if errors.Is(err, incidion.ErrPlanLimit) {
			log.Fatal("deployments need the Pro plan: ", err)
		} else if err != nil {
			log.Fatal(err)
		}
		fmt.Println(id) // keep it for the finish step
	case "finish":
		err := client.DeploymentFinish(ctx, os.Args[2], incidion.DeploymentFinish{
			Status: incidion.DeploymentStatus(os.Args[3]), // success, failed or rolled_back
		})
		if err != nil {
			log.Fatal(err)
		}
	}
}
# .github/workflows/deploy.yml
- id: deploy_start
  run: echo "id=$(go run ./tools/deploy start)" >> "$GITHUB_OUTPUT"
  env:
    INCIDION_SECRET_KEY: ${{ secrets.INCIDION_SECRET_KEY }}
    INCIDION_PROJECT_ID: ${{ vars.INCIDION_PROJECT_ID }}
- run: ./deploy.sh
- if: always()
  run: go run ./tools/deploy finish "${{ steps.deploy_start.outputs.id }}" "${{ job.status == 'success' && 'success' || 'failed' }}"
  env:
    INCIDION_SECRET_KEY: ${{ secrets.INCIDION_SECRET_KEY }}
    INCIDION_PROJECT_ID: ${{ vars.INCIDION_PROJECT_ID }}

DeploymentStart also takes CommitMessage, Trigger ("ci", the default, "manual" or "rollback"; anything else is an error before any request) and Changes ([]incidion.Change{{Hash: "9fceb02", Message: "feat: ...", Author: "...", Type: "feat"}}). DeploymentFinish takes Status (DeploymentSuccess, the default, DeploymentFailed, DeploymentRolledBack), ErrorMessage and BuildSteps ([]incidion.BuildStep{{Name: "test", Status: "success", DurationSeconds: 82}}). Both run synchronously (15 s timeout). See Deployments.

Flush and close

err := client.Flush(ctx)                   // send what is queued now
undelivered, err := client.Close(ctx)      // flush, stop; waits until ctx's deadline (5 s without one)
  • HTTP servers: close after Shutdown:
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go srv.ListenAndServe()
<-ctx.Done()

shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = srv.Shutdown(shutdown)
_, _ = client.Close(shutdown)
  • AWS Lambda and other serverless functions: the process is frozen between invocations. Call client.Flush(ctx) before the handler returns.
  • CLI tools and cron jobs: defer client.Close(ctx) in main, or call Close before os.Exit and log.Fatal, which skip defers.

Delivery

  • Logs and metrics are sent every FlushInterval, or at once when BatchSize entries wait. Requests carry at most BatchSize entries and time out after 30 s.
  • 429 and 503: the batch is kept and every send pauses for the server’s Retry-After (capped by MaxRetryDelay), up to MaxRetries times.
  • 502, 504 and network errors: retried after 2, 4, 8, 16, then 30 s.
  • 413: the batch is sent again in halves.
  • Other 4xx: the batch is dropped and reported. Rows the ingest rejects one by one are reported with their reasons (the first 5).
  • Beyond MaxQueueSize waiting entries the oldest are dropped (reported at most every 10 s).
  • Flush(ctx) sends what is queued now (entries the API asked to hold stay queued) and returns ctx’s error if it ends first.
  • Close(ctx) makes one last attempt at everything queued, even during a pause, and waits for a request in flight, until ctx’s deadline (5 s without one). It returns the number of logs and metrics it could not deliver, with an error wrapping ErrUndelivered. Later logs are dropped.

Errors

Call On failure
New ErrMissingAPIKey when neither key is set; an error matching ErrInvalidEnvironmentID when EnvironmentID is not a UUID
Logs, metrics Never return errors; problems go to ErrorLog
Flush ctx’s error when it ends first
Close undelivered > 0 with an error wrapping ErrUndelivered
Heartbeat, HeartbeatStart *APIError for an HTTP error, or the network error
Job The function’s error
DeploymentStart, DeploymentFinish *APIError (matches ErrPlanLimit, ErrUnauthorized), a network error, or a plain error for a missing ProjectID or secret key, or an unknown Trigger
var apiErr *incidion.APIError
switch {
case errors.Is(err, incidion.ErrPlanLimit): // HTTP 403 PlanLimitExceeded (APIError.PlanLimit has the details)
case errors.Is(err, incidion.ErrUnauthorized): // HTTP 401
case errors.As(err, &apiErr):
	log.Printf("HTTP %d %s: %s", apiErr.StatusCode, apiErr.Code, apiErr.Message)
}

APIError has StatusCode, Code, Message, Details, PlanLimit and URL.

Troubleshooting

ErrorLog shows 401 from the ingest, or a warning that APIKey is a secret key. Logs and metrics need the public key (pk_...). Set the sk_ key as SecretKey (CI only) and the pk_ key as APIKey.

DeploymentStart returns an error matching ErrPlanLimit. The organization is on the Free plan; deployments need Pro or higher. See Plans and Limits.

Nothing arrives. The program exited before the background goroutine sent the batch: Close was skipped (os.Exit, log.Fatal) or never called. Call Close before exiting, or Flush at the end of a serverless invocation.

Still nothing. Set Debug: os.Stderr to see every request with its status, each batch flushed and every dropped entry.