The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
Docs updated
ddux890f879552a9
diff --git a/docs/pages/_meta.json b/docs/pages/_meta.jsonindex 5d716e3c..05b2707c 100644--- a/docs/pages/_meta.json+++ b/docs/pages/_meta.json@@ -1,5 +1,8 @@{"index": "Introduction","getting-started": "Getting Started",- "go-client": "Go Client SDK"+ "architecture": "Architecture",+ "go-client": "Go Client SDK",+ "gin-middleware": "Gin Middleware",+ "http-middleware": "HTTP Middleware"}diff --git a/docs/pages/architecture/_meta.json b/docs/pages/architecture/_meta.jsonnew file mode 100644index 00000000..442fde9b--- /dev/null+++ b/docs/pages/architecture/_meta.json@@ -0,0 +1,7 @@+{+ "index": "Overview",+ "traces": "Traces",+ "issues": "Issues",+ "attributes": "Attributes",+ "spans": "Spans"+}diff --git a/docs/pages/architecture/attributes.mdx b/docs/pages/architecture/attributes.mdxnew file mode 100644index 00000000..6d9ad130--- /dev/null+++ b/docs/pages/architecture/attributes.mdx@@ -0,0 +1,62 @@+# Attributes++Attributes are key-value metadata attached to traces and issues. They provide the context you need to debug problems — who was affected, what they were doing, and in what environment.++## Values++Attribute values are always strings. If the string contains valid JSON, the Traceway dashboard will display it with proper formatting (syntax highlighting, collapsible sections).++```go+// Simple string value+attributes.SetTag("user_id", "12345")++// JSON value — displayed formatted in the dashboard+attributes.SetTagJson("cart_items", []string{"item1", "item2", "item3"})+```++## Scope Levels++### Global Attributes++Set once at application startup. Applied to every trace and issue.++```go+traceway.ConfigureAttributes(func(s *traceway.Attributes) {+ s.SetTag("environment", "production")+ s.SetTag("region", "us-east-1")+ s.SetTag("service", "user-api")+})+```++### Per-Request Attributes++Set during request handling via middleware context. Applied to the current trace and any issues captured during that request.++```go+func handler(c *gin.Context) {+ attributes := traceway.GetAttributesFromContext(c.Request.Context())+ attributes.SetTag("user_id", c.Param("id"))+ attributes.SetTag("tenant", "acme-corp")+}+```++## Inheritance++Per-request attributes start as a clone of the global attributes. Request-level tags override global tags if they share the same key.++```+Global Attributes Request Attributes Final Tags+───────────────── ────────────────── ──────────+environment: prod + user_id: 123 = environment: prod+region: us-east-1 tenant: acme region: us-east-1+service: user-api service: user-api+ user_id: 123+ tenant: acme+```++## What Carries Attributes++- **Traces** (endpoints and tasks) — attributes are recorded with the trace+- **Issues** (exceptions and messages) — attributes in scope at capture time are attached to the issue++In the dashboard, attributes appear in the detail view for endpoints, tasks, and issues.diff --git a/docs/pages/architecture/index.mdx b/docs/pages/architecture/index.mdxnew file mode 100644index 00000000..e62e2289--- /dev/null+++ b/docs/pages/architecture/index.mdx@@ -0,0 +1,72 @@+# Architecture Overview++Traceway organizes your application telemetry around two building blocks: **Traces** and **Issues**. Everything else — spans, attributes, metrics — enriches these two concepts.++## Building Blocks++```+┌──────────────────────────────────────────────────────┐+│ Trace │+│ (Endpoint or Task) │+│ │+│ ┌────────┐ ┌────────────┐ ┌──────────────────┐ │+│ │ Span 1 │ │ Span 2 │ │ Span 3 │ │+│ └────────┘ └────────────┘ └──────────────────┘ │+│ │+│ Attributes: { user_id: "123", tenant: "acme" } │+└──────────────────────────────────────────────────────┘+ │+ │ linked via traceId+ ▼+┌──────────────────────────────────────────────────────┐+│ Issue │+│ (Exception or Message) │+│ │+│ Attributes: { user_id: "123", url: "/api/users" } │+└──────────────────────────────────────────────────────┘+```++### Traces++A **Trace** is a timed unit of work. There are two specializations:++- **Endpoints** — HTTP requests, automatically created by middleware (e.g., `GET /api/users/:id`)+- **Tasks** — Background jobs, manually created in your code (e.g., cron jobs, queue workers)++Both carry duration, attributes, and spans. [Learn more →](/architecture/traces)++### Issues++An **Issue** captures a problem — an exception, a panic, or an explicitly sent message. Issues can be **connected to a trace** via the trace's context, linking the error to the request or task that caused it.++Similar exceptions are automatically grouped by normalized stack trace hash. [Learn more →](/architecture/issues)++### Attributes++**Attributes** are key-value metadata attached to traces and issues. Values are strings — if the string is valid JSON, the dashboard displays it with proper formatting.++Attributes flow from global scope to per-request scope. [Learn more →](/architecture/attributes)++### Spans++**Spans** are timed sub-operations within a trace. Use them to measure where time is spent — database queries, API calls, business logic steps.++Spans display as a timeline within a trace in the dashboard. [Learn more →](/architecture/spans)++## Request Flow++Here's how the concepts connect in a typical request:++1. **Request arrives** → Middleware creates a new **Trace** (Endpoint type)+2. **Auth middleware runs** → Adds `user_id` to **Attributes**+3. **Handler executes** → Creates **Spans** for sub-operations (DB queries, API calls)+4. **Error occurs** → **Issue** captured with full attributes context, linked to the trace+5. **Request completes** → Trace recorded with duration, status code, and all spans+6. **Background** → System **Metrics** collected every 30 seconds++All this data flows to your Traceway dashboard where you can:++- Sort endpoints by impact to find the worst performers+- Get notified when errors happen+- Track task durations over time+- Monitor system health through metricsdiff --git a/docs/pages/architecture/issues.mdx b/docs/pages/architecture/issues.mdxnew file mode 100644index 00000000..70400a73--- /dev/null+++ b/docs/pages/architecture/issues.mdx@@ -0,0 +1,60 @@+# Issues++Issues capture problems in your application — exceptions, panics, and explicitly sent messages.++## What Creates an Issue++An issue is created when:++- A **panic** occurs during a traced request or task+- An **error** is passed to `c.Error()` in Gin+- Your code explicitly calls `CaptureException`, `CaptureMessage`, or related functions++## Errors vs Messages++Traceway captures two kinds of issues:++- **Errors** — Runtime exceptions with stack traces (panics, captured errors)+- **Messages** — Explicitly captured strings via `CaptureMessage("something happened")`++Both appear in the Issues list with full context and attributes.++## Connection to Traces++Issues can be **linked to a trace** via context. When an exception occurs during an HTTP request or background task, the trace ID is automatically attached to the issue.++This linkage means:++- Viewing an issue shows which endpoint or task triggered it+- Viewing a trace shows any issues that occurred during execution+- Attributes from the trace context are included in the issue++Issues captured outside of a trace context (no active request or task) are recorded as standalone issues without a trace link.++## Automatic Grouping++Traceway groups similar exceptions into a single issue by normalizing stack traces:++- Variable values (user IDs, timestamps) are replaced with placeholders+- Memory addresses and file paths are normalized+- UUIDs, IP addresses, and numeric IDs are generalized+- A hash is generated from the normalized trace++This means the same bug produces one issue, not thousands of duplicates with different runtime data.++## Issue Lifecycle++1. **Active** — When an issue first occurs+2. **Archived** — Marked as resolved by you (hidden from the default view)+3. **Reopened** — An archived issue that occurred again (regression detected)++## Attributes on Issues++Issues carry their own attributes — the key-value metadata that was in scope when the exception occurred. If the issue is linked to a trace, it inherits the trace's attributes.++When error recording flags are enabled in middleware, additional context is attached:++- Request URL+- Query parameters+- Request body (JSON only, max 64KB)+- Request headersdiff --git a/docs/pages/architecture/spans.mdx b/docs/pages/architecture/spans.mdxnew file mode 100644index 00000000..f20e3d23--- /dev/null+++ b/docs/pages/architecture/spans.mdx@@ -0,0 +1,64 @@+# Spans++Spans are timed sub-operations within a trace. They show where time is spent during request processing or background task execution.++## What Spans Capture++Each span records:++| Field | Description |+|-------|-------------|+| ID | Unique span identifier |+| Name | Descriptive name you provide |+| Start Time | When the span started |+| Duration | Time elapsed (calculated on `End()`) |++## Use Cases++Spans are useful for timing:++- Database queries+- External API calls+- Cache operations+- File I/O+- Business logic steps++## Viewing Spans++In the dashboard:++1. Navigate to the **Endpoints** or **Tasks** page+2. Click on an entry to see its details+3. Individual traces show their spans as a timeline+4. Each span displays its name and duration++This helps identify bottlenecks — if a request takes 500ms and 450ms is in a database span, you know where to optimize.++## Naming Conventions++Use hierarchical, descriptive names for easy filtering:++```+db.users.find+db.orders.insert+api.stripe.charge+api.sendgrid.send+cache.redis.get+logic.pricing.calculate+```++The pattern `category.resource.action` keeps span names consistent and searchable across your codebase.++## Nesting++Spans can be nested for hierarchical tracking. The parent span encompasses the child spans:++```+Total: 200ms+├── process.checkout: 200ms+│ ├── process.checkout.validate: 20ms+│ ├── process.checkout.charge: 150ms+│ └── process.checkout.fulfill: 30ms+```++Nesting is achieved by starting child spans before ending the parent span. All spans are attached to the same trace context.diff --git a/docs/pages/architecture/traces.mdx b/docs/pages/architecture/traces.mdxnew file mode 100644index 00000000..64773c86--- /dev/null+++ b/docs/pages/architecture/traces.mdx@@ -0,0 +1,66 @@+# Traces++A **Trace** is a timed unit of work in your application. Every HTTP request and background job that Traceway records is a trace.++## Trace Types++### Endpoints++Endpoints are traces created automatically by middleware for HTTP requests. Each endpoint is identified by its HTTP method and route pattern:++```+GET /api/users/:id+POST /api/orders+DELETE /api/sessions/:token+```++Endpoints are ordered in the dashboard by **Impact**, which factors in both performance and error frequency.++The middleware captures:++| Field | Description |+|-------|-------------|+| Endpoint | HTTP method + route template |+| Duration | Request processing time |+| Status Code | HTTP response status |+| Body Size | Response body size in bytes |+| Client IP | Request origin IP address |+| Attributes | Key-value metadata |+| Spans | Timed sub-operations |++### Tasks++Tasks are traces created manually for background operations that run outside HTTP requests:++- Cron jobs+- Queue workers+- Data migrations+- Scheduled reports++Tasks carry the same data as endpoints (duration, attributes, spans) but without HTTP-specific fields like status code or client IP.++## Trace Lifecycle++1. A trace is created — either automatically by middleware (endpoint) or manually via `StartTrace` / `MeasureTask` (task)+2. During execution, spans and attributes are added to the trace via context+3. If an error occurs, an issue is captured and linked to the trace via its ID+4. When the work completes, the trace is recorded with its final duration and all collected data++## Trace Identity++Each trace gets a unique UUID. This ID links:++- The trace record itself (endpoint name, duration, status)+- Any spans created during execution+- Any issues (exceptions/messages) captured during the trace++When you view an issue in the dashboard, you can navigate to the trace that caused it, and vice versa.++## Sampling++Not every trace needs to be recorded. Traceway supports two sample rates:++- **Sample rate** — Controls what percentage of normal traces are recorded (default: 100%)+- **Error sample rate** — Controls what percentage of error traces are recorded (default: 100%)++Error traces (panics, status >= 500, Gin errors) use the error sample rate, which you typically keep at 100% to capture all problems.diff --git a/docs/pages/getting-started/_meta.json b/docs/pages/getting-started/_meta.jsonindex f4129a96..c2ce9d12 100644--- a/docs/pages/getting-started/_meta.json+++ b/docs/pages/getting-started/_meta.json@@ -1,6 +1,4 @@{"local-setup": "Local Setup",- "docker": "Docker Deployment",- "main-concepts": "Main Concepts",- "go-client": "Go Client"+ "docker": "Docker Deployment"}diff --git a/docs/pages/getting-started/go-client.mdx b/docs/pages/getting-started/go-client.mdxdeleted file mode 100644index b4dc0bb9..00000000--- a/docs/pages/getting-started/go-client.mdx+++ /dev/null@@ -1,73 +0,0 @@-# Go Client--The Traceway Go Client SDK provides automatic instrumentation for your Go applications. It captures HTTP transactions, exceptions, background tasks, and system metrics with minimal configuration.--## Getting Your Project Token--Before using the SDK, you need a project token from Traceway:--### 1. Register an Account--When you first access Traceway, the login page will redirect you to registration if no users exist. Create your account with:--- Email address-- Password--### 2. Create an Organization--After registration, you'll be prompted to create an organization. Organizations allow you to:--- Group related projects together-- Invite team members-- Manage access permissions--### 3. Create a Project--Within your organization, create a project for your application:--1. Click "New Project"-2. Enter a project name-3. Select your framework (e.g., "Go - Gin")-4. Copy the generated project token--The project token format is a UUID string like: `550e8400-e29b-41d4-a716-446655440000`--## Installation--Install the Go client SDK:--```bash-go get github.com/tracewayapp/go-client-```--## Connection String Format--The SDK uses a connection string to configure the backend endpoint:--```-<project_token>@<backend_url>-```--Examples:-```-550e8400-e29b-41d4-a716-446655440000@http://localhost:8082/api/report-your-token@https://traceway.example.com/api/report-```--## How Data Collection Works--The SDK uses a **ring buffer batching system** for efficient data collection:--1. **Collection**: Data is collected into a "frame" (transactions, exceptions, metrics)-2. **Batching**: Frames accumulate for a configurable interval (default: 5 seconds)-3. **Upload**: Completed frames are compressed (gzip) and sent to the backend-4. **Retry**: Failed uploads remain in the buffer for retry--This design minimizes network overhead and handles temporary connectivity issues gracefully.--## Next Steps--- [Main Concepts](/getting-started/main-concepts) - Understand Endpoints, Issues, Tasks, Metrics, and Attributes-- [Gin Framework](/go-client/gin/quickstart) - Quick start guide for Gin integration-- [Attributes](/go-client/attributes) - Add contextual tags to your telemetry-- [Segments](/go-client/segments) - Track sub-operations within transactionsdiff --git a/docs/pages/getting-started/local-setup.mdx b/docs/pages/getting-started/local-setup.mdxindex 5d964633..783dc791 100644--- a/docs/pages/getting-started/local-setup.mdx+++ b/docs/pages/getting-started/local-setup.mdx@@ -132,7 +132,7 @@ func main() {}```-See the [Go Client documentation](/go-client/overview) for detailed SDK usage.+See the [Go Client documentation](/go-client) for detailed SDK usage.## Troubleshootingdiff --git a/docs/pages/getting-started/main-concepts.mdx b/docs/pages/getting-started/main-concepts.mdxdeleted file mode 100644index 66b53896..00000000--- a/docs/pages/getting-started/main-concepts.mdx+++ /dev/null@@ -1,125 +0,0 @@-# Main Concepts--Traceway organizes your application telemetry into five core concepts: Endpoints, Issues, Tasks, Metrics, and Attributes. Understanding these concepts will help you get the most out of your monitoring setup.--## Endpoints--Endpoints represent HTTP transactions in your application. Each endpoint is identified by its HTTP method and route pattern (e.g., `GET /api/users/:id`). Endpoints are ordered based on their Impact which takes into account the performance of the endpoint as well as how often it happens to behave poorly.--## Issues--Issues are exceptions (errors and panics) captured from your application as well as messages. Traceway automatically groups similar exceptions so the same logical error appears as one issue. Issues can contain their own Attributes and they can be connected to a transaction or a task.--### Error vs Message--Traceway captures two types of exceptions:--- **Errors** - Runtime exceptions with stack traces (panics, thrown errors)-- **Messages** - Explicitly captured errors via `traceway.CaptureMessage("a string with some value")`--Both appear in the Issues list with full context.--### Automatic Grouping--Exceptions are grouped by normalizing their stack traces:--- Variable values (user IDs, timestamps) are replaced with placeholders-- Memory addresses and file paths are normalized-- A hash is generated from the normalized trace--This means the same bug produces one issue, not thousands of duplicates with different user data.--### Issue Lifecycle--1. **Active** - When an issue originally happens-2. **Archived** - Marked as resolved by you (doesn't show up until it's reopened)-3. **Reopened** - Archived issue that occurred again (regression)--## Context Tags--Attributes can be captured on Endpoints/Issues/Tasks.-They are a map of key value pairs that give you extra context related to the instance you are reviewing.-If the value is JSON it will be displayed formatted on the website.--Tags help you understand who was affected and what they were doing.--## Tasks--Tasks are background operations that run outside of HTTP requests. Examples include:--- Cron jobs-- Queue workers-- Data migrations-- Scheduled reports-- Long running tasks--## Segments--You can break Endpoinst and Tasks into segments to see where time is spent:--```-Total: 45s-├── task.fetch_data: 5s (11%)-├── task.process: 35s (78%)-└── task.upload: 5s (11%)-```--This helps identify bottlenecks within long-running operations.--## Metrics--Metrics are time-series measurements of your application's health. They're collected automatically and can be extended with custom metrics.--### System Metrics (Automatic)--| Metric | Description |-| ----------------- | ---------------------- |-| `cpu.used_pcnt` | CPU usage percentage |-| `mem.used` | Memory usage in MB |-| `go.go_routines` | Active goroutine count |-| `go.heap_objects` | Objects on the heap |-| `go.num_gc` | Total GC cycles |-| `go.gc_pause` | Last GC pause duration |--### Custom Metrics--Capture application-specific measurements:--```go-traceway.CaptureMetric("queue.depth", float64(len(queue)))-traceway.CaptureMetric("cache.hit_rate", hitRate)-traceway.CaptureMetric("active.users", float64(activeUsers))-```--Custom metrics are currently not being displayed on the website.--### What to Look For--- **Memory growth** - Continuous increase suggests a leak-- **Goroutine growth** - Unbounded increase indicates goroutine leak-- **GC frequency** - High frequency means allocation pressure-- **CPU spikes** - Correlate with specific endpoints or tasks--## Putting It Together--Here's how the concepts connect in a typical request flow:--1. **Request arrives** → Creates a new transaction (Endpoint)-2. **Auth middleware runs** → Adds user_id to Attributes-3. **Handler executes** → May create Segments for sub-operations-4. **Error occurs** → Issue captured with full Attributes context-5. **Request completes** → Transaction recorded with duration-6. **Background** → Metrics collected every 30 seconds-7. **Tasks** → Capture all async (outside of the endpoints) code execution into Tasks--All this data flows to your Traceway dashboard where you can:--- Sort endpoints by Impact to find the worst performers and fix them-- Get notified when errors happen to escalate-- Track task durations over time-- Monitor system health through metrics--## Next Steps--- [Go Client Quickstart](/go-client/gin/quickstart) - Set up the SDK-- [Attributes Documentation](/go-client/attributes) - Deep dive into attributesdiff --git a/docs/pages/gin-middleware/_meta.json b/docs/pages/gin-middleware/_meta.jsonnew file mode 100644index 00000000..00073156--- /dev/null+++ b/docs/pages/gin-middleware/_meta.json@@ -0,0 +1,5 @@+{+ "index": "Quick Start",+ "configuration": "Configuration",+ "error-recording": "Error Recording"+}diff --git a/docs/pages/gin-middleware/configuration.mdx b/docs/pages/gin-middleware/configuration.mdxnew file mode 100644index 00000000..ac33cee7--- /dev/null+++ b/docs/pages/gin-middleware/configuration.mdx@@ -0,0 +1,147 @@+# Gin Middleware Configuration++## Middleware Options++| Option | Description | Default |+|--------|-------------|---------|+| `WithRepanic(bool)` | Re-panic after capturing, letting upstream recovery handle it | `true` |+| `WithRecordUnmatched(bool)` | Record requests for unregistered routes (404s) | `false` |+| `WithRecordStatic(bool)` | Record requests for static file routes | `false` |+| `WithIgnoredPaths(...string)` | Skip recording for specific route paths | none |+| `WithOnErrorRecording(RecordingFlag)` | What additional data to capture on errors | `0` (none) |++## Passthrough Core Options++These options are forwarded to the core `traceway` client:++| Option | Description | Default |+|--------|-------------|---------|+| `WithDebug(bool)` | Enable debug logging | `false` |+| `WithVersion(string)` | Application version shown in dashboard | `""` |+| `WithServerName(string)` | Server hostname identifier | Auto-detected |+| `WithSampleRate(float64)` | Percentage of normal traces to record (0.0–1.0) | `1.0` |+| `WithErrorSampleRate(float64)` | Percentage of error traces to record (0.0–1.0) | `1.0` |+| `WithCollectionInterval(time.Duration)` | How often batched data is sent | `5s` |+| `WithMaxCollectionFrames(int)` | Maximum frames to buffer | `12` |+| `WithUploadTimeout(time.Duration)` | HTTP upload timeout | `2s` |+| `WithMetricsInterval(time.Duration)` | System metrics collection interval | `30s` |++## Repanic Behavior++When `WithRepanic(true)` (default), the middleware re-panics after capturing the stack trace. This allows upstream recovery middleware (like `gin.Recovery()`) to handle the panic.++When `WithRepanic(false)`, the middleware calls `c.AbortWithStatus(500)` and does not re-panic.++## Route Filtering++### Unmatched Routes++By default, requests to unregistered routes (404s) are **not recorded**. The request is passed through but no trace is created.++```go+tracewaygin.WithRecordUnmatched(true) // Record 404 requests+```++When enabled, the raw URL path is used as the endpoint name instead of a route template.++### Static Routes++Requests served by Gin's `StaticFile`, `Static`, or `StaticFS` handlers are **not recorded** by default:++```go+tracewaygin.WithRecordStatic(true) // Record static file requests+```++### Ignored Paths++Skip recording for specific route paths:++```go+tracewaygin.WithIgnoredPaths("/health", "/ready", "/metrics")+```++Ignored paths are still served — the request passes through to your handler, but no trace is recorded.++## Complete Example++```go+package main++import (+ "time"++ "github.com/gin-gonic/gin"+ traceway "go.tracewayapp.com"+ tracewaygin "go.tracewayapp.com/traceway_gin"+)++func main() {+ traceway.ConfigureAttributes(func(s *traceway.Attributes) {+ s.SetTag("environment", "production")+ s.SetTag("service", "user-api")+ })++ router := gin.Default()++ router.Use(tracewaygin.New(+ "your-token@http://localhost:8082/api/report",+ tracewaygin.WithVersion("1.2.3"),+ tracewaygin.WithServerName("api-server-01"),+ tracewaygin.WithRepanic(true),+ tracewaygin.WithRecordUnmatched(false),+ tracewaygin.WithRecordStatic(false),+ tracewaygin.WithIgnoredPaths("/health", "/ready"),+ tracewaygin.WithOnErrorRecording(+ tracewaygin.RecordingUrl | tracewaygin.RecordingQuery,+ ),+ tracewaygin.WithCollectionInterval(5 * time.Second),+ tracewaygin.WithMetricsInterval(30 * time.Second),+ ))++ router.GET("/api/users/:id", getUser)+ router.Run(":8080")+}+```++## Configuration Recommendations++### Development++```go+tracewaygin.New(+ connectionString,+ tracewaygin.WithDebug(true),+ tracewaygin.WithOnErrorRecording(+ tracewaygin.RecordingUrl |+ tracewaygin.RecordingQuery |+ tracewaygin.RecordingHeader |+ tracewaygin.RecordingBody,+ ),+)+```++### Production++```go+tracewaygin.New(+ connectionString,+ tracewaygin.WithVersion(os.Getenv("APP_VERSION")),+ tracewaygin.WithServerName(os.Getenv("HOSTNAME")),+ tracewaygin.WithOnErrorRecording(+ tracewaygin.RecordingUrl | tracewaygin.RecordingQuery,+ ),+)+```++### High-Traffic Services++```go+tracewaygin.New(+ connectionString,+ tracewaygin.WithSampleRate(0.1),+ tracewaygin.WithErrorSampleRate(1.0),+ tracewaygin.WithCollectionInterval(10 * time.Second),+ tracewaygin.WithMaxCollectionFrames(20),+ tracewaygin.WithMetricsInterval(60 * time.Second),+)+```diff --git a/docs/pages/gin-middleware/error-recording.mdx b/docs/pages/gin-middleware/error-recording.mdxnew file mode 100644index 00000000..fe34cc6e--- /dev/null+++ b/docs/pages/gin-middleware/error-recording.mdx@@ -0,0 +1,83 @@+# Gin Error Recording++When an exception occurs during a request (panic, Gin error, or status >= 500), you can control what additional request data is captured alongside the stack trace.++## Recording Flags++Configure error recording with `WithOnErrorRecording`:++```go+tracewaygin.New(+ connectionString,+ tracewaygin.WithOnErrorRecording(+ tracewaygin.RecordingUrl | tracewaygin.RecordingQuery,+ ),+)+```++### Available Flags++| Flag | Description | Privacy Impact |+|------|-------------|----------------|+| `RecordingUrl` | Request URL path | Low |+| `RecordingQuery` | Query parameters as JSON | Medium |+| `RecordingBody` | Request body (JSON content-type only, max 64KB) | High |+| `RecordingHeader` | Request headers as JSON | High |++### Combining Flags++Flags are combined with the `|` operator:++```go+// Record URL and query parameters+tracewaygin.RecordingUrl | tracewaygin.RecordingQuery++// Record everything+tracewaygin.RecordingUrl | tracewaygin.RecordingQuery | tracewaygin.RecordingBody | tracewaygin.RecordingHeader+```++## Body Capture Details++Body recording has two constraints:++- **Content-Type must be `application/json`** — non-JSON bodies are not captured+- **Maximum size is 64KB** — bodies larger than 64KB are truncated++After reading the body for capture, it is restored so downstream handlers can still read it.++## Privacy Considerations++Body and header recording may capture sensitive data:++- Authentication tokens in headers+- Personal information in request bodies+- API keys in query parameters++Use minimal recording flags in production:++```go+// Production — limited data+tracewaygin.WithOnErrorRecording(+ tracewaygin.RecordingUrl | tracewaygin.RecordingQuery,+)++// Development — full request data+tracewaygin.WithOnErrorRecording(+ tracewaygin.RecordingUrl |+ tracewaygin.RecordingQuery |+ tracewaygin.RecordingBody |+ tracewaygin.RecordingHeader,+)+```++## Captured Data Format++Recorded data is attached as attributes on the issue:++| Attribute Key | Value |+|---------------|-------|+| `url` | URL path string |+| `query` | JSON-encoded query parameters |+| `body` | Raw request body string |+| `headers` | JSON-encoded request headers |+| `user agent` | User-Agent header value (always captured on error) |diff --git a/docs/pages/gin-middleware/index.mdx b/docs/pages/gin-middleware/index.mdxnew file mode 100644index 00000000..8ed888ff--- /dev/null+++ b/docs/pages/gin-middleware/index.mdx@@ -0,0 +1,96 @@+# Gin Middleware++The `traceway_gin` package provides middleware for the [Gin](https://gin-gonic.com/) web framework. It automatically creates a trace for each request, captures panics, and detects errors from Gin's error chain.++## Installation++```bash+go get go.tracewayapp.com+```++## Basic Setup++```go+package main++import (+ "github.com/gin-gonic/gin"+ tracewaygin "go.tracewayapp.com/traceway_gin"+)++func main() {+ router := gin.Default()++ // Add Traceway middleware (must be before routes)+ router.Use(tracewaygin.New(+ "your-token@http://localhost:8082/api/report",+ ))++ router.GET("/api/users", getUsers)+ router.POST("/api/users", createUser)++ router.Run(":8080")+}+```++`New` returns a `gin.HandlerFunc` and calls `traceway.Init` internally — do not call `Init` separately.++## What Gets Captured++The middleware automatically captures for every request:++| Data | Description |+|------|-------------|+| **Endpoint** | HTTP method + route template (e.g., `GET /api/users/:id`) |+| **Duration** | Request processing time |+| **Status Code** | HTTP response status |+| **Body Size** | Response body size in bytes |+| **Client IP** | From Gin's `ClientIP()` |+| **Panics** | Recovered and captured with full stack trace |+| **Gin Errors** | Errors added via `c.Error()` |++## Error Detection++A request is considered an error when any of these are true:++- A **panic** occurred during handler execution+- **Gin context errors** exist (`c.Errors` is non-empty)+- The response **status code is >= 500**++Error traces use the error sample rate for sampling decisions.++## Panic Recovery++When a panic occurs, the middleware:++1. Recovers the panic+2. Captures the full stack trace as an issue+3. Either re-panics (default, `WithRepanic(true)`) or calls `c.AbortWithStatus(500)`++```go+func riskyHandler(c *gin.Context) {+ panic("something went wrong")+ // Stack trace is captured, linked to this request's trace+}+```++## Gin Error Chain++Errors added via `c.Error()` are captured as separate issues:++```go+func handler(c *gin.Context) {+ if err := doSomething(); err != nil {+ c.Error(err) // Captured as an issue+ c.AbortWithStatus(500)+ return+ }+}+```++If the error wraps a `StackTraceError` (from `traceway.NewStackTraceErrorf`), the embedded stack frames are used. Otherwise, the error type and message are recorded.++## Next Steps++- [Configuration](/gin-middleware/configuration) — All options including route filtering and passthrough settings+- [Error Recording](/gin-middleware/error-recording) — Control what request data is captured on errorsdiff --git a/docs/pages/go-client/_meta.json b/docs/pages/go-client/_meta.jsonindex 913509fe..739735de 100644--- a/docs/pages/go-client/_meta.json+++ b/docs/pages/go-client/_meta.json@@ -1,5 +1,11 @@{- "gin": "Gin Framework",+ "index": "Overview",+ "initialization": "Initialization",+ "traces": "Traces",+ "spans": "Spans",+ "exceptions": "Exceptions",+ "messages": "Messages",+ "metrics": "Metrics","attributes": "Attributes",- "segments": "Segments"+ "stack-traces": "Stack Traces"}diff --git a/docs/pages/go-client/attributes.mdx b/docs/pages/go-client/attributes.mdxindex 4ff78576..36ffaf0e 100644--- a/docs/pages/go-client/attributes.mdx+++ b/docs/pages/go-client/attributes.mdx@@ -1,103 +1,116 @@# Attributes-Attributes attach contextual tags to exceptions and transactions, making it easier to debug and filter issues in the dashboard.+Attributes attach key-value metadata to traces and issues. The `Attributes` type is thread-safe and available through both global configuration and per-request context.-## Request Attributes+## Attributes API-Add contextual information specific to a single request:+### SetTag++Set a string attribute:```go-import tracewaygin "github.com/tracewayapp/go-client/traceway_gin"+attributes.SetTag("user_id", "12345")+attributes.SetTag("tenant", "acme-corp")+```++### SetTagJson++Set an attribute with a JSON-serialized value. The value is marshaled to JSON and stored as a string. In the dashboard, JSON values are displayed with formatting.-func handler(c *gin.Context) {- attributes := tracewaygin.GetAttributesFromGin(c)+```go+attributes.SetTagJson("cart_items", []string{"item1", "item2", "item3"})+attributes.SetTagJson("user_prefs", map[string]bool{"notifications": true})+```- // Add tags that will be attached to any exceptions in this request- attributes.SetTag("user_id", c.Param("id"))- attributes.SetTag("tenant", "acme-corp")- attributes.SetTag("feature_flag", "new_checkout")+Returns an error if JSON marshaling fails.- // ... rest of handler+### GetTag++Retrieve a single attribute value:++```go+value, ok := attributes.GetTag("user_id")+if ok {+ fmt.Println("User:", value)}```-Request attribute tags are automatically included when:+### GetTags++Get a copy of all attributes as a `map[string]string`:-- Exceptions are captured during the request-- The transaction is recorded-- Segments are tracked+```go+allTags := attributes.GetTags()+for k, v := range allTags {+ fmt.Printf("%s = %s\n", k, v)+}+```-## Attributes Methods+Returns a copy — modifying the returned map does not affect the original attributes.-| Method | Description |-| ----------------------------------- | ---------------------------------------------- |-| `SetTag(key, value string)` | Set a string tag |-| `SetTagJson(key string, value any)` | Set a JSON-serialized tag (for complex values) |-| `GetTag(key string)` | Retrieve a tag value |-| `GetTags()` | Get a copy of all tags |+### Clone-### Examples+Create an independent copy of the attributes:```go-// String tags-attributes.SetTag("user_id", "12345")-attributes.SetTag("organization", "acme-corp")+copy := attributes.Clone()+copy.SetTag("extra", "value") // Does not affect original+```-// JSON tags for complex values-attributes.SetTagJson("cart_items", []string{"item1", "item2", "item3"})-attributes.SetTagJson("user_prefs", map[string]bool{"notifications": true})+### Clear-// Reading tags-userID := attributes.GetTag("user_id")-allTags := attributes.GetTags()+Remove all attributes:++```go+attributes.Clear()```-## Attributes in Middleware+## Global Attributes++### ConfigureAttributes-Add tags for all requests in a middleware function:+Set attributes that apply to all traces and issues. Call once at application startup:```go-func authMiddleware() gin.HandlerFunc {- return func(c *gin.Context) {- user := authenticate(c)+traceway.ConfigureAttributes(func(s *traceway.Attributes) {+ s.SetTag("environment", "production")+ s.SetTag("region", "us-east-1")+ s.SetTag("service", "user-api")+ s.SetTag("version", os.Getenv("APP_VERSION"))+})+```- // Add user info to attributes for all downstream handlers- attributes := tracewaygin.GetAttributesFromGin(c)- attributes.SetTag("user_id", user.ID)- attributes.SetTag("user_email", user.Email)- attributes.SetTag("organization", user.OrgID)- attributes.SetTag("role", user.Role)+Global attributes are inherited by every request's attribute set.- c.Next()- }-}+## Context-Based Attributes++### WithAttributes++Create a new context with a cloned and modified attribute set:++```go+ctx = traceway.WithAttributes(ctx, func(a *traceway.Attributes) {+ a.SetTag("operation", "checkout")+ a.SetTag("step", "payment")+})```-## Global Attributes+This clones the attributes from the current context, applies the modifications, and stores the new set in the returned context. The original context's attributes are unchanged.-Global attribute tags apply to all telemetry data. Configure them once at application startup:+### GetAttributesFromContext++Retrieve attributes from a Go context:```go-import "github.com/tracewayapp/go-client/traceway"--func main() {- // Configure global attributes (runs once at startup)- traceway.ConfigureAttributes(func(s *traceway.Attributes) {- s.SetTag("environment", "production")- s.SetTag("region", "us-east-1")- s.SetTag("service", "user-api")- s.SetTag("version", os.Getenv("APP_VERSION"))- })-- // ... rest of your application-}+attributes := traceway.GetAttributesFromContext(ctx)+attributes.SetTag("user_id", userID)```-Global tags are inherited by every request's attributes and background task.+If the context has no attributes, returns a clone of the global attributes. If the context is `nil`, also returns a clone of the global attributes.-## Tag Inheritance+## Attribute Inheritance-Tags flow from global to request attributes:+Per-request attributes start as a clone of the global attributes. Request-level values override global values for the same key:```Global Attributes Request Attributes Final Tags@@ -109,66 +122,30 @@ service: user-api service: user-apitenant: acme```-Request-level tags override global tags if they have the same key.--## Best Practices+## Usage in Middleware-### 1. Set Global Context at Startup--```go-traceway.ConfigureAttributes(func(s *traceway.Attributes) {- s.SetTag("environment", os.Getenv("ENV"))- s.SetTag("version", version)- s.SetTag("region", os.Getenv("AWS_REGION"))- s.SetTag("service", serviceName)-})-```--### 2. Add User Context in Auth Middleware+Add attributes for all requests in a Gin middleware:```gofunc authMiddleware() gin.HandlerFunc {return func(c *gin.Context) {- if user := getCurrentUser(c); user != nil {- attributes := tracewaygin.GetAttributesFromGin(c)- attributes.SetTag("user_id", user.ID)- attributes.SetTag("organization", user.OrgID)- }+ user := authenticate(c)+ attributes := traceway.GetAttributesFromContext(c.Request.Context())+ attributes.SetTag("user_id", user.ID)+ attributes.SetTag("organization", user.OrgID)c.Next()}}```-### 3. Add Request-Specific Context in Handlers+## Usage in Handlers++Add request-specific attributes:```gofunc createOrderHandler(c *gin.Context) {- attributes := tracewaygin.GetAttributesFromGin(c)+ attributes := traceway.GetAttributesFromContext(c.Request.Context())attributes.SetTag("action", "create_order")attributes.SetTag("item_count", fmt.Sprintf("%d", len(items)))- // ... rest of handler}```--### 4. Use Meaningful Tag Names--```go-// Good - descriptive and searchable-attributes.SetTag("user_id", userID)-attributes.SetTag("order_id", orderID)-attributes.SetTag("payment_method", "stripe")--// Avoid - too generic-attributes.SetTag("id", someID)-attributes.SetTag("type", "thing")-```--## Viewing Tags in Dashboard--Tags appear in the detail view for:--1. **Exceptions** and **Messages**-2. **Endpoints**-3. **Tasks**--Use tags to debug issues with full contextdiff --git a/docs/pages/go-client/exceptions.mdx b/docs/pages/go-client/exceptions.mdxnew file mode 100644index 00000000..73ce06ec--- /dev/null+++ b/docs/pages/go-client/exceptions.mdx@@ -0,0 +1,141 @@+# Exceptions++The SDK provides multiple ways to capture exceptions, from simple error capture to context-aware variants that link exceptions to traces.++## CaptureException++Capture an error with an automatically generated stack trace:++```go+if err := doSomething(); err != nil {+ traceway.CaptureException(err)+}+```++This creates a standalone issue — not linked to any trace.++## CaptureExceptionWithAttributes++Capture an error with custom attributes and an optional trace ID link:++```go+traceway.CaptureExceptionWithAttributes(+ err,+ map[string]string{"user_id": "123", "action": "checkout"},+ &traceId, // or nil for standalone+)+```++## CaptureExceptionWithContext++Capture an error using the Go context to automatically extract the trace ID, task flag, and attributes:++```go+func handler(c *gin.Context) {+ ctx := c.Request.Context()++ if err := doSomething(); err != nil {+ traceway.CaptureExceptionWithContext(ctx, err)+ c.AbortWithStatus(500)+ return+ }+}+```++This is the recommended way to capture exceptions within traced requests or tasks — it links the exception to the current trace and includes all in-scope attributes.++## CaptureTraceException++Link an exception to a specific trace by ID:++```go+traceway.CaptureTraceException(traceId, stackTraceString)+```++## CaptureTraceExceptionWithAttributes++Same as above with attributes:++```go+traceway.CaptureTraceExceptionWithAttributes(+ traceId,+ stackTraceString,+ map[string]string{"endpoint": "GET /api/users"},+)+```++## CaptureTaskException++Link an exception to a task trace:++```go+traceway.CaptureTaskException(traceId, stackTraceString)+```++The difference from `CaptureTraceException` is that the issue is marked as belonging to a task rather than an endpoint.++## CaptureTaskExceptionWithAttributes++```go+traceway.CaptureTaskExceptionWithAttributes(+ traceId,+ stackTraceString,+ map[string]string{"task": "report.monthly"},+)+```++## Recover++Recover from panics in goroutines and capture them as issues:++```go+func worker() {+ defer traceway.Recover()++ // If this panics, the stack trace is captured+ riskyOperation()+}+```++`Recover` captures the panic value and stack trace, then swallows the panic (the goroutine exits cleanly).++## RecoverWithContext++Same as `Recover` but includes attributes from the context:++```go+func worker(ctx context.Context) {+ defer traceway.RecoverWithContext(ctx)++ riskyOperation()+}+```++Attributes in the context are attached to the captured issue.++## PanicError++`PanicError` is the error type used when `MeasureTask` re-panics after capturing an exception:++```go+type PanicError struct {+ Value interface{} // The original panic value+ Stack string // Formatted stack trace+}+```++You can check for it when recovering panics from `MeasureTask`:++```go+defer func() {+ if r := recover(); r != nil {+ if pe, ok := r.(*traceway.PanicError); ok {+ log.Printf("Task panicked: %v", pe.Value)+ }+ }+}()++traceway.MeasureTask("risky.task", func(ctx context.Context) {+ panic("something broke")+})+```diff --git a/docs/pages/go-client/gin/_meta.json b/docs/pages/go-client/gin/_meta.jsondeleted file mode 100644index 836a4786..00000000--- a/docs/pages/go-client/gin/_meta.json+++ /dev/null@@ -1,4 +0,0 @@-{- "quickstart": "Quick Start",- "configuration": "Configuration"-}diff --git a/docs/pages/go-client/gin/configuration.mdx b/docs/pages/go-client/gin/configuration.mdxdeleted file mode 100644index 8bc0afb7..00000000--- a/docs/pages/go-client/gin/configuration.mdx+++ /dev/null@@ -1,163 +0,0 @@-# Gin Configuration--Complete reference for all Traceway Gin middleware configuration options.--## Configuration Options--| Option | Description | Default |-|--------|-------------|---------|-| `WithDebug(bool)` | Enables debug logging - prints all captured telemetry to stdout | `false` |-| `WithVersion(string)` | Sets the application version shown in the dashboard | `""` |-| `WithServerName(string)` | Sets the server hostname identifier | Auto-detected |-| `WithRepanic(bool)` | Re-panics after capturing exception, allowing Gin's recovery to handle it | `true` |-| `WithRecordUnmatched(bool)` | Captures 404 requests for unmatched routes | `true` |-| `WithCollectionInterval(duration)` | How often batched telemetry data is sent to the server | `5s` |-| `WithMaxCollectionFrames(int)` | Maximum frames to buffer before forcing send | `12` |-| `WithMetricsInterval(duration)` | How often system metrics (CPU, memory) are collected | `30s` |-| `WithOnErrorRecording(flags)` | What additional data to capture when exceptions occur | `0` (none) |--## Error Recording Flags--When an exception occurs, you can control what additional request data is captured using `WithOnErrorRecording`. Combine flags with the `|` operator.--| Flag | Description | Privacy Impact |-|------|-------------|----------------|-| `RecordingUrl` | Includes the request URL path in exception data | Low |-| `RecordingQuery` | Includes query parameters as JSON | Medium |-| `RecordingHeader` | Includes request headers as JSON | High |-| `RecordingBody` | Includes request body (JSON only, max 64KB) | High |--**Privacy Note**: Body and header recording may capture sensitive data (authentication tokens, personal information). Use with caution in production environments.--### Example: Combining Flags--```go-tracewaygin.WithOnErrorRecording(- tracewaygin.RecordingUrl | tracewaygin.RecordingQuery,-)-```--## Complete Configuration Example--```go-package main--import (- "time"-- "github.com/gin-gonic/gin"- "github.com/tracewayapp/go-client/traceway"- tracewaygin "github.com/tracewayapp/go-client/traceway_gin"-)--func main() {- traceway.ConfigureAttributes(func(s *traceway.Attributes) {- s.SetTag("environment", "production")- s.SetTag("service", "user-api")- })-- router := gin.Default()-- // Add Traceway middleware with full configuration- router.Use(tracewaygin.New(- "your-token@http://localhost:8082/api/report",-- // Debug mode - logs all captured data to stdout- tracewaygin.WithDebug(true),-- // Application version (shown in dashboard)- tracewaygin.WithVersion("1.2.3"),-- // Server hostname- tracewaygin.WithServerName("api-server-01"),-- // Re-panic after capturing (default: true)- // Set to false to let Gin's recovery middleware handle it- tracewaygin.WithRepanic(true),-- // Capture unmatched routes (404s)- tracewaygin.WithRecordUnmatched(true),-- // Control what data is captured on errors- tracewaygin.WithOnErrorRecording(- tracewaygin.RecordingUrl |- tracewaygin.RecordingQuery |- tracewaygin.RecordingHeader |- tracewaygin.RecordingBody,- ),-- // Collection interval (how often batches are sent)- tracewaygin.WithCollectionInterval(5 * time.Second),-- // Maximum frames before forcing send- tracewaygin.WithMaxCollectionFrames(12),-- // Metrics collection interval- tracewaygin.WithMetricsInterval(30 * time.Second),- ))-- // Routes- router.GET("/api/users/:id", func(c *gin.Context) {- attributes := tracewaygin.GetAttributesFromGin(c)- attributes.SetTag("user_id", c.Param("id"))-- // Track database query- ctx := c.Request.Context()- seg := traceway.StartSegment(ctx, "db.users.find")- user, err := findUser(c.Param("id"))- seg.End()-- if err != nil {- c.Error(err)- c.AbortWithStatus(500)- return- }-- c.JSON(200, user)- })-- router.Run(":8080")-}-```--## Configuration Recommendations--### Development--```go-tracewaygin.New(- connectionString,- tracewaygin.WithDebug(true), // See all telemetry in console- tracewaygin.WithOnErrorRecording(- tracewaygin.RecordingUrl |- tracewaygin.RecordingQuery |- tracewaygin.RecordingHeader |- tracewaygin.RecordingBody, // Full request data for debugging- ),-)-```--### Production--```go-tracewaygin.New(- connectionString,- tracewaygin.WithVersion(os.Getenv("APP_VERSION")),- tracewaygin.WithServerName(os.Getenv("HOSTNAME")),- tracewaygin.WithOnErrorRecording(- tracewaygin.RecordingUrl |- tracewaygin.RecordingQuery, // Limited data for privacy- ),-)-```--### High-Traffic Services--```go-tracewaygin.New(- connectionString,- tracewaygin.WithCollectionInterval(10 * time.Second), // Less frequent sends- tracewaygin.WithMaxCollectionFrames(20), // Larger buffer- tracewaygin.WithMetricsInterval(60 * time.Second), // Less frequent metrics-)-```diff --git a/docs/pages/go-client/gin/quickstart.mdx b/docs/pages/go-client/gin/quickstart.mdxdeleted file mode 100644index 04be43c3..00000000--- a/docs/pages/go-client/gin/quickstart.mdx+++ /dev/null@@ -1,103 +0,0 @@-# Gin Framework Quick Start--Get Traceway integrated with your Gin application in under 5 minutes.--## Installation--```bash-go get github.com/tracewayapp/go-client-```--## Basic Setup--Add the Traceway middleware to your Gin router:--```go-package main--import (- "github.com/gin-gonic/gin"- tracewaygin "github.com/tracewayapp/go-client/traceway_gin"-)--func main() {- router := gin.Default()-- // Add Traceway middleware (must be before routes)- router.Use(tracewaygin.New(- "your-token@http://localhost:8082/api/report",- ))-- router.GET("/api/users", getUsers)- router.POST("/api/users", createUser)-- router.Run(":8080")-}-```--## What Gets Captured Automatically--The middleware captures the following for every request:--| Data | Description |-| --------------- | --------------------------------------------------------- |-| **Endpoint** | HTTP method + route template (e.g., "GET /api/users/:id") |-| **Duration** | Request processing time in milliseconds |-| **Status Code** | HTTP response status |-| **Body Size** | Response body size in bytes |-| **Client IP** | Request origin IP address |-| **Panics** | Automatically recovered and captured with stack trace |--## Error Handling--### Automatic Panic Recovery--Panics are automatically recovered and captured:--```go-func riskyHandler(c *gin.Context) {- // This panic will be captured with full stack trace- panic("something went wrong")-}-```--The middleware will:--1. Recover the panic-2. Capture the stack trace-3. Link it to the current transaction-4. Re-panic (if `WithRepanic(true)`) or abort with 500--### Gin Error Chain--Errors added via `c.Error()` are also captured:--```go-func handler(c *gin.Context) {- if err := doSomething(); err != nil {- c.Error(err) // Will be captured as exception- c.AbortWithStatus(500)- return- }- c.JSON(200, gin.H{"ok": true})-}-```--Or alternatively:--```go-func handler(c *gin.Context) {- if err := doSomething(); err != nil {- c.AbortWithError(500, err) // Will be captured as an exception- return- }- c.JSON(200, gin.H{"ok": true})-}-```--## Next Steps--- [Configuration](/go-client/gin/configuration) - All configuration options and error recording flags-- [Attributes](/go-client/attributes) - Add contextual tags to requests-- [Exceptions](/go-client/exceptions) - Manual exception capture-- [Segments](/go-client/segments) - Track sub-operations within requestsdiff --git a/docs/pages/go-client/index.mdx b/docs/pages/go-client/index.mdxnew file mode 100644index 00000000..2f112668--- /dev/null+++ b/docs/pages/go-client/index.mdx@@ -0,0 +1,46 @@+# Go Client SDK++The `traceway` package is the core SDK for instrumenting Go applications. It captures traces, exceptions, messages, metrics, and spans.++## Installation++```bash+go get go.tracewayapp.com+```++## Packages++| Package | Import | Purpose |+|---------|--------|---------|+| Core | `go.tracewayapp.com` | All tracing, exception, message, metric, and span APIs |+| Gin Middleware | `go.tracewayapp.com/traceway_gin` | Automatic instrumentation for Gin applications |+| HTTP Middleware | `go.tracewayapp.com/traceway_http` | Automatic instrumentation for `net/http` servers |+| DB Instrumentation | `go.tracewayapp.com/traceway_db` | Automatic span creation for `database/sql` operations |++## When to Use Core vs Middleware++**Use middleware** ([Gin](/gin-middleware) or [HTTP](/http-middleware)) when your application serves HTTP requests. The middleware handles initialization, trace creation, panic recovery, and data capture automatically.++**Use the core package directly** when:++- Running background tasks or workers (use `MeasureTask` or `StartTrace`)+- Capturing exceptions outside of HTTP context (use `CaptureException`)+- Sending messages (use `CaptureMessage`)+- Adding spans to traced operations (use `StartSpan`)+- Initializing Traceway without middleware (use `Init`)++## Getting Your Project Token++Before using the SDK, you need a project token from your Traceway instance:++1. Register an account on your Traceway dashboard+2. Create an organization+3. Create a project — select your framework (e.g., "Go - Gin")+4. Copy the generated project token (UUID format)++## Next Steps++- [Initialization](/go-client/initialization) — Connection string format and all configuration options+- [Traces](/go-client/traces) — Recording HTTP requests and background tasks+- [Exceptions](/go-client/exceptions) — Capturing errors and panics+- [Spans](/go-client/spans) — Timing sub-operationsdiff --git a/docs/pages/go-client/initialization.mdx b/docs/pages/go-client/initialization.mdxnew file mode 100644index 00000000..c65622a3--- /dev/null+++ b/docs/pages/go-client/initialization.mdx@@ -0,0 +1,85 @@+# Initialization++## Connection String++The SDK uses a connection string to configure the backend endpoint:++```+<project_token>@<api_url>+```++Examples:++```+550e8400-e29b-41d4-a716-446655440000@http://localhost:8082/api/report+your-token@https://traceway.example.com/api/report+```++## Init++Initialize the core client directly when not using middleware:++```go+import traceway "go.tracewayapp.com"++func main() {+ err := traceway.Init(+ "your-token@http://localhost:8082/api/report",+ traceway.WithVersion("1.0.0"),+ traceway.WithDebug(true),+ )+ if err != nil {+ log.Fatal(err)+ }++ // Your application code...+}+```++`Init` can only be called once. A second call returns an error.++When using middleware (`traceway_gin.New` or `traceway_http.New`), initialization is handled automatically — do not call `Init` separately.++## Configuration Options++| Option | Description | Default |+|--------|-------------|---------|+| `WithDebug(bool)` | Enable debug logging — prints captured telemetry to stdout | `false` |+| `WithMaxCollectionFrames(int)` | Maximum frames to buffer in the ring buffer before forcing send | `12` |+| `WithCollectionInterval(time.Duration)` | How often batched telemetry data is sent to the server | `5s` |+| `WithUploadTimeout(time.Duration)` | HTTP timeout for uploading frames to the backend | `2s` |+| `WithMetricsInterval(time.Duration)` | How often system metrics (CPU, memory, goroutines) are collected | `30s` |+| `WithVersion(string)` | Application version shown in the dashboard | `""` |+| `WithServerName(string)` | Server hostname identifier | Auto-detected from `os.Hostname()` |+| `WithSampleRate(float64)` | Percentage of normal traces to record (0.0–1.0) | `1.0` |+| `WithErrorSampleRate(float64)` | Percentage of error traces to record (0.0–1.0) | `1.0` |++## Ring Buffer Batching++The SDK uses a ring buffer system for efficient data collection:++1. **Collection** — Traces, exceptions, and metrics are collected into the current "frame"+2. **Rotation** — After the collection interval (default 5s), the frame is rotated into the send queue+3. **Upload** — Frames in the send queue are compressed (gzip) and sent to the backend+4. **Cleanup** — Successfully uploaded frames are removed from the buffer++If the backend is temporarily unreachable, frames remain in the ring buffer. The buffer holds up to `maxCollectionFrames` (default 12) frames — at the default 5s interval, this means roughly 60 seconds of data is buffered before the oldest frames are dropped.++## Sampling++Sample rates control what percentage of traces are recorded:++```go+traceway.Init(+ connectionString,+ // Record 10% of normal traces+ traceway.WithSampleRate(0.1),+ // Record all error traces+ traceway.WithErrorSampleRate(1.0),+)+```++A trace is considered an error when:+- A panic was recovered+- The HTTP status code is >= 500+- Gin context errors exist (Gin middleware only)diff --git a/docs/pages/go-client/messages.mdx b/docs/pages/go-client/messages.mdxnew file mode 100644index 00000000..180bce97--- /dev/null+++ b/docs/pages/go-client/messages.mdx@@ -0,0 +1,60 @@+# Messages++Messages are explicitly captured strings that appear as issues in the dashboard. Unlike exceptions, messages don't carry automatic stack traces — they record whatever string you provide.++## CaptureMessage++Capture a standalone message:++```go+traceway.CaptureMessage("User exceeded rate limit")+```++This creates an issue with no trace link and no attributes beyond the message itself.++## CaptureMessageWithContext++Capture a message with trace linkage and attributes from the Go context:++```go+func handler(c *gin.Context) {+ ctx := c.Request.Context()++ if user.RequestCount > rateLimit {+ traceway.CaptureMessageWithContext(ctx, "Rate limit exceeded for user")+ }+}+```++This links the message to the current trace and includes all in-scope attributes (user ID, tenant, etc.).++## CaptureMessageAttributes++Capture a message with explicit attributes:++```go+traceway.CaptureMessageAttributes(+ "Payment processing delayed",+ map[string]string{+ "payment_id": paymentID,+ "delay_ms": fmt.Sprintf("%d", delayMs),+ "provider": "stripe",+ },+)+```++This creates a standalone message (no trace link) with the provided attributes.++## When to Use Messages vs Exceptions++Use **exceptions** (`CaptureException`) for actual errors — things that shouldn't happen and need stack traces for debugging.++Use **messages** (`CaptureMessage`) for notable events that aren't errors:++- Rate limit hits+- Feature flag activations+- Degraded service notifications+- Business rule violations+- Audit events++Both appear in the Issues list, but messages are marked distinctly from errors.diff --git a/docs/pages/go-client/metrics.mdx b/docs/pages/go-client/metrics.mdxnew file mode 100644index 00000000..6e36d854--- /dev/null+++ b/docs/pages/go-client/metrics.mdx@@ -0,0 +1,76 @@+# Metrics++Metrics are time-series measurements of your application's health. System metrics are collected automatically; you can also capture custom metrics.++## CaptureMetric++Record a metric value:++```go+traceway.CaptureMetric("queue.depth", float64(len(queue)))+traceway.CaptureMetric("cache.hit_rate", hitRate)+traceway.CaptureMetric("active.users", float64(activeUsers))+```++Each call records the metric name, value, and current timestamp.++## Automatic System Metrics++The SDK automatically collects system metrics at the configured interval (default: 30 seconds):++| Metric Constant | Name | Description |+|-----------------|------|-------------|+| `MetricNameCpuUsage` | `cpu.used_pcnt` | CPU usage percentage |+| `MetricNameMemoryUsage` | `mem.used` | Memory usage in MB |+| `MetricNameMemoryTotal` | `mem.total` | Total system memory in MB |+| `MetricNameGoRoutines` | `go.go_routines` | Active goroutine count |+| `MetricNameHeapObjects` | `go.heap_objects` | Objects on the heap |+| `MetricNameNumGC` | `go.num_gc` | Total GC cycles |+| `MetricNameGCPauseTotal` | `go.gc_pause` | Total GC pause time in nanoseconds |++## Custom Metrics++Capture application-specific measurements anywhere in your code:++```go+// Queue monitoring+traceway.CaptureMetric("queue.depth", float64(len(queue)))+traceway.CaptureMetric("queue.processing_rate", itemsPerSecond)++// Cache performance+traceway.CaptureMetric("cache.hit_rate", hits / total)+traceway.CaptureMetric("cache.size", float64(cache.Len()))++// Business metrics+traceway.CaptureMetric("active.users", float64(activeUsers))+traceway.CaptureMetric("orders.per_minute", orderRate)+```++Custom metrics are not currently displayed on the dashboard.++## What to Look For++- **Memory growth** — Continuous increase suggests a memory leak+- **Goroutine growth** — Unbounded increase indicates goroutine leak+- **GC frequency** — High `num_gc` growth means allocation pressure+- **CPU spikes** — Correlate with specific endpoints or tasks++## Metrics Interval++Control how often system metrics are collected:++```go+traceway.Init(+ connectionString,+ traceway.WithMetricsInterval(60 * time.Second), // Collect every 60s instead of 30s+)+```++Or via middleware:++```go+tracewaygin.New(+ connectionString,+ tracewaygin.WithMetricsInterval(60 * time.Second),+)+```diff --git a/docs/pages/go-client/segments.mdx b/docs/pages/go-client/segments.mdxdeleted file mode 100644index 7e2d21a2..00000000--- a/docs/pages/go-client/segments.mdx+++ /dev/null@@ -1,284 +0,0 @@-# Segments--Segments track sub-operations within a transaction, helping you understand where time is spent during request processing or background task execution.--## Common Use Cases--- Database queries-- External API calls-- Cache operations-- File I/O-- Business logic steps--## Basic Usage--```go-import "github.com/tracewayapp/go-client/traceway"--func handler(c *gin.Context) {- ctx := c.Request.Context()-- // Start a segment- seg := traceway.StartSegment(ctx, "database.users.find")-- // Do the operation- user, err := db.FindUser(userID)-- // End the segment (records duration)- seg.End()-- if err != nil {- c.Error(err)- return- }-- c.JSON(200, user)-}-```--## Naming Conventions--Use hierarchical, descriptive names for easy filtering and analysis:--```go-// Database operations-traceway.StartSegment(ctx, "db.users.find")-traceway.StartSegment(ctx, "db.orders.insert")-traceway.StartSegment(ctx, "db.products.update")--// External APIs-traceway.StartSegment(ctx, "api.stripe.charge")-traceway.StartSegment(ctx, "api.sendgrid.send")-traceway.StartSegment(ctx, "api.s3.upload")--// Cache operations-traceway.StartSegment(ctx, "cache.redis.get")-traceway.StartSegment(ctx, "cache.redis.set")--// Business logic-traceway.StartSegment(ctx, "logic.pricing.calculate")-traceway.StartSegment(ctx, "logic.validation.order")-```--### Naming Constants--For consistency across your codebase, define naming constants:--```go-const (- SegmentDBQuery = "db.%s.%s" // db.users.find- SegmentAPICall = "api.%s.%s" // api.stripe.charge- SegmentCacheOp = "cache.%s.%s" // cache.redis.get-)--seg := traceway.StartSegment(ctx, fmt.Sprintf(SegmentDBQuery, "orders", "find"))-```--## Multiple Segments--Track multiple operations in sequence:--```go-func processOrder(ctx context.Context, orderID string) error {- // Fetch order- seg := traceway.StartSegment(ctx, "db.orders.find")- order, err := db.GetOrder(orderID)- seg.End()- if err != nil {- return err- }-- // Validate inventory- seg = traceway.StartSegment(ctx, "logic.inventory.check")- available := checkInventory(order.Items)- seg.End()- if !available {- return errors.New("items unavailable")- }-- // Charge payment- seg = traceway.StartSegment(ctx, "api.stripe.charge")- err = stripe.Charge(order.PaymentMethod, order.Total)- seg.End()- if err != nil {- return err- }-- // Update order status- seg = traceway.StartSegment(ctx, "db.orders.update")- err = db.UpdateOrderStatus(orderID, "paid")- seg.End()-- return err-}-```--## Nested Segments--Segments can be nested for hierarchical tracking:--```go-func handler(c *gin.Context) {- ctx := c.Request.Context()-- // Parent segment- seg := traceway.StartSegment(ctx, "process.checkout")-- // Child segments- childSeg := traceway.StartSegment(ctx, "process.checkout.validate")- validate(cart)- childSeg.End()-- childSeg = traceway.StartSegment(ctx, "process.checkout.charge")- charge(payment)- childSeg.End()-- childSeg = traceway.StartSegment(ctx, "process.checkout.fulfill")- fulfill(order)- childSeg.End()-- seg.End()-}-```--## Segments in Background Tasks--Segments work with both HTTP transactions and background tasks:--```go-func generateReport(ctx context.Context) {- traceway.MeasureTask("report.monthly", func(ctx context.Context) {- // Track data fetching- seg := traceway.StartSegment(ctx, "report.fetch_data")- data := fetchReportData()- seg.End()-- // Track processing- seg = traceway.StartSegment(ctx, "report.process")- result := processData(data)- seg.End()-- // Track upload- seg = traceway.StartSegment(ctx, "report.upload")- uploadToS3(result)- seg.End()- })-}-```--## Segment Data--Each segment captures:--| Field | Description |-|-------|-------------|-| `id` | Unique segment identifier |-| `name` | Descriptive name you provide |-| `start_time` | When the segment started |-| `duration` | Time spent (calculated on `End()`) |--## Using Defer for Safety--Use defer to ensure segments end even when errors occur:--```go-func fetchData(ctx context.Context) (*Data, error) {- seg := traceway.StartSegment(ctx, "api.external.fetch")- defer seg.End() // Ensures segment ends even on error-- resp, err := http.Get(url)- if err != nil {- return nil, err- }- return parseResponse(resp)-}-```--## Viewing Segments in Dashboard--In the dashboard:-1. Navigate to the **Endpoints** page-2. Click on an endpoint to see details-3. Individual transactions show their segments-4. Segments display as a timeline within the transaction--## Best Practices--### 1. Track Meaningful Operations--Track significant operations, not every function call:--```go-// Good - tracks significant operation-seg := traceway.StartSegment(ctx, "db.users.find")-user := db.Query("SELECT * FROM users WHERE id = ?", id)-seg.End()--// Too granular - avoid this-seg := traceway.StartSegment(ctx, "db.prepare")-stmt := db.Prepare(query)-seg.End()-seg = traceway.StartSegment(ctx, "db.execute")-result := stmt.Execute(id)-seg.End()-```--### 2. Always End Segments--Unended segments won't appear in the dashboard:--```go-// Use defer for operations that might error-seg := traceway.StartSegment(ctx, "risky.operation")-defer seg.End()--// Or explicitly end in all code paths-seg := traceway.StartSegment(ctx, "operation")-result, err := doWork()-seg.End() // End before returning-if err != nil {- return nil, err-}-return result, nil-```--### 3. Keep Names Consistent--Use the same naming pattern across your codebase for easy filtering:--```go-// Consistent: category.resource.action-"db.users.find"-"db.users.insert"-"db.orders.find"-"api.stripe.charge"-"cache.redis.get"-```--### 4. Don't Over-Segment--Balance detail with overhead:--```go-// Good - key operations tracked-seg := traceway.StartSegment(ctx, "db.users.find")-user := findUser(id)-seg.End()--seg = traceway.StartSegment(ctx, "api.payment.charge")-chargeUser(user, amount)-seg.End()--// Over-segmented - too much noise-seg := traceway.StartSegment(ctx, "validate.input")-validateInput(input)-seg.End()--seg = traceway.StartSegment(ctx, "parse.json")-data := parseJSON(input)-seg.End()--seg = traceway.StartSegment(ctx, "check.nil")-checkNotNil(data)-seg.End()-```diff --git a/docs/pages/go-client/spans.mdx b/docs/pages/go-client/spans.mdxnew file mode 100644index 00000000..af015272--- /dev/null+++ b/docs/pages/go-client/spans.mdx@@ -0,0 +1,136 @@+# Spans++Spans track timed sub-operations within a trace. Use them to measure where time is spent during request processing or task execution.++## StartSpan++Create a span within an active trace:++```go+func handler(c *gin.Context) {+ ctx := c.Request.Context()++ span := traceway.StartSpan(ctx, "db.users.find")+ user, err := db.FindUser(userID)+ span.End()++ if err != nil {+ c.Error(err)+ return+ }+ c.JSON(200, user)+}+```++`StartSpan` requires a context that carries a `TraceContext` (created by middleware or `StartTrace`). If no trace context exists, it returns `nil`.++## The Defer Pattern++Use `defer` to ensure spans are ended even when errors or panics occur:++```go+func fetchData(ctx context.Context) (*Data, error) {+ span := traceway.StartSpan(ctx, "api.external.fetch")+ defer span.End()++ resp, err := http.Get(url)+ if err != nil {+ return nil, err+ }+ return parseResponse(resp)+}+```++`End()` is safe to call on a `nil` span and safe to call multiple times — only the first call records the duration.++## Multiple Spans++Track sequential operations:++```go+func processOrder(ctx context.Context, orderID string) error {+ span := traceway.StartSpan(ctx, "db.orders.find")+ order, err := db.GetOrder(orderID)+ span.End()+ if err != nil {+ return err+ }++ span = traceway.StartSpan(ctx, "logic.inventory.check")+ available := checkInventory(order.Items)+ span.End()+ if !available {+ return errors.New("items unavailable")+ }++ span = traceway.StartSpan(ctx, "api.stripe.charge")+ err = stripe.Charge(order.PaymentMethod, order.Total)+ span.End()++ return err+}+```++## Nesting++Spans can be nested by starting child spans before ending the parent:++```go+func handler(c *gin.Context) {+ ctx := c.Request.Context()++ parent := traceway.StartSpan(ctx, "process.checkout")++ child := traceway.StartSpan(ctx, "process.checkout.validate")+ validate(cart)+ child.End()++ child = traceway.StartSpan(ctx, "process.checkout.charge")+ charge(payment)+ child.End()++ parent.End()+}+```++All spans are attached to the same trace context regardless of nesting depth.++## Spans in Background Tasks++Spans work within `MeasureTask`:++```go+traceway.MeasureTask("report.monthly", func(ctx context.Context) {+ span := traceway.StartSpan(ctx, "report.fetch_data")+ data := fetchReportData()+ span.End()++ span = traceway.StartSpan(ctx, "report.process")+ result := processData(data)+ span.End()++ span = traceway.StartSpan(ctx, "report.upload")+ uploadToS3(result)+ span.End()+})+```++## Naming Conventions++Use hierarchical names following `category.resource.action`:++```go+// Database operations+traceway.StartSpan(ctx, "db.users.find")+traceway.StartSpan(ctx, "db.orders.insert")++// External APIs+traceway.StartSpan(ctx, "api.stripe.charge")+traceway.StartSpan(ctx, "api.s3.upload")++// Cache operations+traceway.StartSpan(ctx, "cache.redis.get")++// Business logic+traceway.StartSpan(ctx, "logic.pricing.calculate")+```diff --git a/docs/pages/go-client/stack-traces.mdx b/docs/pages/go-client/stack-traces.mdxnew file mode 100644index 00000000..8e4228c3--- /dev/null+++ b/docs/pages/go-client/stack-traces.mdx@@ -0,0 +1,99 @@+# Stack Traces++The SDK provides utilities for creating errors with embedded stack traces and formatting stack trace output.++## NewStackTraceErrorf++Create an error with an embedded stack trace, using `fmt.Errorf`-style formatting:++```go+err := traceway.NewStackTraceErrorf("failed to process order %s: %w", orderID, originalErr)+```++Returns a `*StackTraceError` that implements the `error` interface. The stack trace is captured at the call site.++If the wrapped error (`%w`) already contains a `StackTraceError`, the existing stack frames are preserved instead of capturing new ones. This prevents duplicate stack traces when wrapping errors up the call chain.++## WrapWithStackTrace++Wrap an existing error with a stack trace:++```go+result, err := db.Query(query)+if err != nil {+ return traceway.WrapWithStackTrace(err, 0)+}+```++The `skip` parameter controls how many stack frames to skip (0 captures from the call site).++## StackTraceError Type++Both `NewStackTraceErrorf` and `WrapWithStackTrace` return `*StackTraceError`:++```go+type StackTraceError struct {+ Err error+ Frames []runtime.Frame+}+```++Methods:++| Method | Description |+|--------|-------------|+| `Error() string` | Returns the underlying error's message |+| `Unwrap() error` | Returns the wrapped error (for `errors.Is`/`errors.As`) |+| `GetStackFrames() []runtime.Frame` | Returns the captured stack frames |++`StackTraceError` integrates with Go's error wrapping — `errors.Is` and `errors.As` work through it.++## Why Use StackTraceError++When you pass errors to Gin's `c.Error(err)`, the Gin middleware checks if the error contains a `StackTraceError`. If it does, the embedded stack frames are used for the issue's stack trace instead of capturing at the middleware level.++This gives you accurate stack traces that point to where the error actually originated:++```go+func handler(c *gin.Context) {+ user, err := findUser(c.Param("id"))+ if err != nil {+ // The stack trace will point to findUser, not this handler+ c.Error(traceway.NewStackTraceErrorf("user lookup failed: %w", err))+ c.AbortWithStatus(500)+ return+ }+ c.JSON(200, user)+}+```++## CaptureStack++Capture the current call stack as `[]runtime.Frame`:++```go+frames := traceway.CaptureStack(0) // 0 = capture from call site+```++The `skip` parameter controls how many frames to skip from the top.++## FormatErrorWithStack++Format an error and stack frames into a human-readable string:++```go+frames := traceway.CaptureStack(0)+formatted := traceway.FormatErrorWithStack(err, frames)+```++Output format:++```+*errors.errorString: connection refused+Dial()+ /app/net/dial.go:42+Connect()+ /app/db/connect.go:15+handler()+ /app/api/handler.go:28+```diff --git a/docs/pages/go-client/traces.mdx b/docs/pages/go-client/traces.mdxnew file mode 100644index 00000000..8d0ec918--- /dev/null+++ b/docs/pages/go-client/traces.mdx@@ -0,0 +1,110 @@+# Traces++The core SDK provides functions for creating and recording traces — both for HTTP endpoints and background tasks.++## StartTrace++Creates a new trace context and stores it in the Go context. Use this when you need manual control over trace creation outside of middleware.++```go+ctx := traceway.StartTrace(context.Background())++// The context now carries a TraceContext with a unique ID+// Use this context for spans, exceptions, and attributes+```++## GetTraceFromContext++Retrieves the current trace context from a Go context:++```go+tc := traceway.GetTraceFromContext(ctx)+if tc != nil {+ fmt.Println("Trace ID:", tc.Id)+}+```++## CaptureTrace++Records a completed HTTP trace. Typically called by middleware — you rarely need this directly.++```go+traceway.CaptureTrace(+ tc, // *TraceContext+ "GET /api/users", // endpoint+ duration, // time.Duration+ startedAt, // time.Time+ 200, // statusCode+ 1024, // bodySize+ "192.168.1.1", // clientIP+)+```++## CaptureTraceWithAttributes++Same as `CaptureTrace` but includes attributes:++```go+traceway.CaptureTraceWithAttributes(+ tc,+ "GET /api/users",+ duration,+ startedAt,+ 200,+ 1024,+ "192.168.1.1",+ map[string]string{"user_id": "123", "tenant": "acme"},+)+```++## CaptureTask++Records a completed background task:++```go+tc := &traceway.TraceContext{+ Id: uuid.NewString(),+ IsTask: true,+}++start := time.Now()+// ... do work ...+duration := time.Since(start)++traceway.CaptureTask(+ tc,+ "report.monthly", // task name+ duration,+ start,+ map[string]string{"report_type": "revenue"},+)+```++## MeasureTask++A convenience wrapper that creates a trace context, measures execution time, captures the task, and handles panics:++```go+traceway.MeasureTask("email.send_batch", func(ctx context.Context) {+ // ctx carries a TraceContext and Attributes+ // You can add spans and attributes here++ span := traceway.StartSpan(ctx, "email.fetch_recipients")+ recipients := fetchRecipients()+ span.End()++ span = traceway.StartSpan(ctx, "email.send_all")+ sendEmails(recipients)+ span.End()+})+```++`MeasureTask` automatically:++- Creates a `TraceContext` with `IsTask: true`+- Creates an `Attributes` instance available via context+- Measures execution duration+- Records the task trace via `CaptureTask`+- Recovers panics — captures the stack trace as an issue, then re-panics++If the function panics, both the task trace and the exception are recorded before the panic propagates.diff --git a/docs/pages/http-middleware/_meta.json b/docs/pages/http-middleware/_meta.jsonnew file mode 100644index 00000000..00073156--- /dev/null+++ b/docs/pages/http-middleware/_meta.json@@ -0,0 +1,5 @@+{+ "index": "Quick Start",+ "configuration": "Configuration",+ "error-recording": "Error Recording"+}diff --git a/docs/pages/http-middleware/configuration.mdx b/docs/pages/http-middleware/configuration.mdxnew file mode 100644index 00000000..d97a5dfb--- /dev/null+++ b/docs/pages/http-middleware/configuration.mdx@@ -0,0 +1,118 @@+# HTTP Middleware Configuration++## Middleware Options++| Option | Description | Default |+|--------|-------------|---------|+| `WithRepanic(bool)` | Re-panic after capturing, letting upstream recovery handle it | `true` |+| `WithIgnoredPaths(...string)` | Skip recording for specific URL paths | none |+| `WithFilter(func(*http.Request) bool)` | Custom filter function — return `false` to skip recording | none |+| `WithOnErrorRecording(RecordingFlag)` | What additional data to capture on errors | `0` (none) |++## Passthrough Core Options++These options are forwarded to the core `traceway` client:++| Option | Description | Default |+|--------|-------------|---------|+| `WithDebug(bool)` | Enable debug logging | `false` |+| `WithVersion(string)` | Application version shown in dashboard | `""` |+| `WithServerName(string)` | Server hostname identifier | Auto-detected |+| `WithSampleRate(float64)` | Percentage of normal traces to record (0.0–1.0) | `1.0` |+| `WithErrorSampleRate(float64)` | Percentage of error traces to record (0.0–1.0) | `1.0` |+| `WithCollectionInterval(time.Duration)` | How often batched data is sent | `5s` |+| `WithMaxCollectionFrames(int)` | Maximum frames to buffer | `12` |+| `WithUploadTimeout(time.Duration)` | HTTP upload timeout | `2s` |+| `WithMetricsInterval(time.Duration)` | System metrics collection interval | `30s` |++## Repanic Behavior++When `WithRepanic(true)` (default), the middleware re-panics after capturing the stack trace. This allows upstream recovery middleware to handle the panic as well.++When `WithRepanic(false)`, the middleware responds with HTTP 500 and does not re-panic.++## Path Filtering++### WithIgnoredPaths++Skip recording for specific paths:++```go+tracewayhttp.New(+ connectionString,+ tracewayhttp.WithIgnoredPaths("/health", "/ready", "/metrics"),+)+```++Ignored paths are still served — the request passes through to your handler, but no trace is recorded.++### WithFilter++For dynamic filtering logic, use `WithFilter`. Return `false` to skip recording:++```go+tracewayhttp.New(+ connectionString,+ tracewayhttp.WithFilter(func(r *http.Request) bool {+ // Skip internal service-to-service calls+ if r.Header.Get("X-Internal") == "true" {+ return false+ }+ // Skip static assets+ if strings.HasPrefix(r.URL.Path, "/static/") {+ return false+ }+ return true+ }),+)+```++When the filter returns `false`, the request is passed directly to your handler without any Traceway wrapping.++## Differences from Gin Middleware++The HTTP middleware does **not** have `WithRecordUnmatched` or `WithRecordStatic` options — these are Gin-specific because `net/http` has no built-in route registration to distinguish matched vs unmatched routes.++Instead, the HTTP middleware provides `WithFilter` for custom request filtering, which is not available in the Gin middleware.++## Complete Example++```go+package main++import (+ "net/http"+ "time"++ traceway "go.tracewayapp.com"+ tracewayhttp "go.tracewayapp.com/traceway_http"+)++func main() {+ traceway.ConfigureAttributes(func(s *traceway.Attributes) {+ s.SetTag("environment", "production")+ s.SetTag("service", "order-api")+ })++ mux := http.NewServeMux()+ mux.HandleFunc("/api/orders", handleOrders)++ handler := tracewayhttp.New(+ "your-token@http://localhost:8082/api/report",+ tracewayhttp.WithVersion("1.2.3"),+ tracewayhttp.WithServerName("api-server-01"),+ tracewayhttp.WithRepanic(true),+ tracewayhttp.WithIgnoredPaths("/health", "/ready"),+ tracewayhttp.WithFilter(func(r *http.Request) bool {+ return r.Header.Get("X-Internal") != "true"+ }),+ tracewayhttp.WithOnErrorRecording(+ tracewayhttp.RecordingUrl | tracewayhttp.RecordingQuery,+ ),+ tracewayhttp.WithCollectionInterval(5 * time.Second),+ tracewayhttp.WithMetricsInterval(30 * time.Second),+ )(mux)++ http.ListenAndServe(":8080", handler)+}+```diff --git a/docs/pages/http-middleware/error-recording.mdx b/docs/pages/http-middleware/error-recording.mdxnew file mode 100644index 00000000..ab3c184a--- /dev/null+++ b/docs/pages/http-middleware/error-recording.mdx@@ -0,0 +1,85 @@+# HTTP Error Recording++When an exception occurs during a request, you can control what additional request data is captured alongside the stack trace.++## Recording Flags++Configure error recording with `WithOnErrorRecording`:++```go+tracewayhttp.New(+ connectionString,+ tracewayhttp.WithOnErrorRecording(+ tracewayhttp.RecordingUrl | tracewayhttp.RecordingQuery,+ ),+)+```++### Available Flags++| Flag | Description | Privacy Impact |+|------|-------------|----------------|+| `RecordingUrl` | Request URL path | Low |+| `RecordingQuery` | Query parameters as JSON | Medium |+| `RecordingBody` | Request body (JSON content-type only, max 64KB) | High |+| `RecordingHeader` | Request headers as JSON | High |++### Combining Flags++Flags are combined with the `|` operator:++```go+// Record URL and query parameters+tracewayhttp.RecordingUrl | tracewayhttp.RecordingQuery++// Record everything+tracewayhttp.RecordingUrl | tracewayhttp.RecordingQuery | tracewayhttp.RecordingBody | tracewayhttp.RecordingHeader+```++## Body Capture Details++Body recording has two constraints:++- **Content-Type must be `application/json`** — non-JSON bodies are not captured+- **Maximum size is 64KB** — bodies larger than 64KB are truncated++After reading the body for capture, it is **restored** so downstream handlers can still read it. The body is reconstructed using `io.MultiReader` with the captured bytes and the remaining body.++## Privacy Considerations++Body and header recording may capture sensitive data:++- Authentication tokens in headers+- Personal information in request bodies+- API keys in query parameters++Use minimal recording flags in production. A recommended production setup:++```go+tracewayhttp.WithOnErrorRecording(+ tracewayhttp.RecordingUrl | tracewayhttp.RecordingQuery,+)+```++Reserve full recording for development environments:++```go+tracewayhttp.WithOnErrorRecording(+ tracewayhttp.RecordingUrl |+ tracewayhttp.RecordingQuery |+ tracewayhttp.RecordingBody |+ tracewayhttp.RecordingHeader,+)+```++## Captured Data Format++Recorded data is attached as attributes on the issue:++| Attribute Key | Value |+|---------------|-------|+| `url` | URL path string |+| `query` | JSON-encoded query parameters |+| `body` | Raw request body string |+| `headers` | JSON-encoded request headers |+| `user agent` | User-Agent header value (always captured on error) |diff --git a/docs/pages/http-middleware/index.mdx b/docs/pages/http-middleware/index.mdxnew file mode 100644index 00000000..d2c3bcc3--- /dev/null+++ b/docs/pages/http-middleware/index.mdx@@ -0,0 +1,83 @@+# HTTP Middleware++The `traceway_http` package provides middleware for standard `net/http` servers. It automatically creates a trace for each request, captures panics, and detects client IP addresses.++## Installation++```bash+go get go.tracewayapp.com+```++## Basic Setup++```go+package main++import (+ "net/http"++ tracewayhttp "go.tracewayapp.com/traceway_http"+)++func main() {+ mux := http.NewServeMux()+ mux.HandleFunc("/api/users", getUsers)+ mux.HandleFunc("/api/orders", getOrders)++ // Wrap with Traceway middleware+ handler := tracewayhttp.New(+ "your-token@http://localhost:8082/api/report",+ )(mux)++ http.ListenAndServe(":8080", handler)+}+```++The `New` function returns `func(http.Handler) http.Handler`, so you chain it around your handler.++## What Gets Captured++The middleware automatically captures for every request:++| Data | Description |+|------|-------------|+| **Endpoint** | HTTP method + URL path (e.g., `GET /api/users`) |+| **Duration** | Request processing time |+| **Status Code** | HTTP response status |+| **Body Size** | Response body size in bytes |+| **Client IP** | Detected from headers or connection |+| **Panics** | Recovered and captured with full stack trace |++## ResponseWriter Wrapping++The middleware wraps the `http.ResponseWriter` to track the response status code and bytes written. The wrapped writer preserves the original writer's `Flusher`, `Hijacker`, and `Unwrap` interfaces.++## Client IP Detection++Client IP is resolved in this order:++1. `X-Forwarded-For` header (first IP in the list)+2. `X-Real-IP` header+3. `RemoteAddr` from the connection++## Error Detection++A request is considered an error when:++- A **panic** occurs during handler execution+- The response status code is **>= 500**++Error traces use the error sample rate for sampling decisions.++## Panic Handling++When a panic occurs, the middleware:++1. Recovers the panic+2. Captures the full stack trace as an issue+3. Either re-panics (default, `WithRepanic(true)`) or responds with 500++## Next Steps++- [Configuration](/http-middleware/configuration) — All options and passthrough settings+- [Error Recording](/http-middleware/error-recording) — Control what request data is captured on errorsdiff --git a/docs/pages/index.mdx b/docs/pages/index.mdxindex b8cd4987..dbb035c9 100644--- a/docs/pages/index.mdx+++ b/docs/pages/index.mdx@@ -39,7 +39,7 @@ Traceway consists of three main components:- **Automatic Error Capture**: Panics and errors are automatically captured with full context- **Request Scoping**: Add custom tags (user ID, tenant, etc.) to correlate errors-- **Segment Tracking**: Measure sub-operations within requests (database queries, API calls)+- **Span Tracking**: Measure sub-operations within requests (database queries, API calls)- **Background Task Support**: Track non-HTTP operations with the same tooling### For Operations@@ -55,12 +55,12 @@ Currently, Traceway provides official SDK support for:| Framework | Status | Documentation || --------- | ------ | --------------------------------- |-| Gin (Go) | Stable | [Go Client - Gin](/go-client/gin) |--More framework support is planned for future releases.+| Gin (Go) | Stable | [Gin Middleware](/gin-middleware) |+| net/http | Stable | [HTTP Middleware](/http-middleware) |## Next Steps- [Local Setup](/getting-started/local-setup) - Run Traceway on your machine- [Docker Deployment](/getting-started/docker) - Deploy with Docker-- [Go Client Overview](/go-client/overview) - Learn about the SDK+- [Architecture](/architecture) - Understand traces, issues, spans, and attributes+- [Go Client SDK](/go-client) - Learn about the core SDK