Skip to content

Update sampling APIs, examples, and docs assets#2

Merged
spa5k merged 5 commits intomainfrom
feat/sampling-api-docs-refresh
Feb 9, 2026
Merged

Update sampling APIs, examples, and docs assets#2
spa5k merged 5 commits intomainfrom
feat/sampling-api-docs-refresh

Conversation

@spa5k
Copy link
Contributor

@spa5k spa5k commented Feb 9, 2026

refine sampling configuration and example usage across the package

  • add focused sampling examples under cmd/examples
  • add updated demo and branding assets used in docs

Summary by CodeRabbit

  • New Features

    • Composable sampling framework supporting rate limiting, error keeping, path filtering, and duration-based conditions
    • New API functions to inspect event fields, errors, and start times
  • Documentation

    • Expanded Quick Start guide with examples for net/http, slog, zap, zerolog, gin, echo, and fiber integrations
    • Added interactive example sections with runnable code samples and API helper documentation

- Added new examples for `net/http`, `gin`, `fiber v2`, `fiber v3`, and `echo` using `slog` for structured logging.
- Included runnable reference applications in `cmd/examples`.
- Improved organization of the "More Examples" section for better clarity.
…mpling configuration

- Modified `options.go` to clarify the default behavior of `SamplingRate`.
- Updated all example applications to use a consistent request route format: `/users/{id}`.
- Enhanced error handling and logging in each example to support debugging and failure scenarios.
- Adjusted server ports for each example to avoid conflicts and ensure clarity in usage.
…stom samplers, and ensure TestSink deep copies event fields.
@coderabbitai
Copy link

coderabbitai bot commented Feb 9, 2026

Warning

Rate limit exceeded

@spa5k has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 20 minutes and 39 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📝 Walkthrough

Walkthrough

This pull request introduces a composable sampling framework for request filtering, adds event accessor helper functions, and expands example programs across multiple adapters and routers with enriched logging handlers following a consistent request pattern (/users/{id} with context enrichment, debug controls, and failure simulation).

Changes

Cohort / File(s) Summary
Documentation
README.md, cmd/examples/README.md
Expanded quick start section with code examples for slog, zap, zerolog, gin, echo, fiber, and interactive details blocks; added port map, curl commands, and API helper variants.
Adapter Examples
cmd/examples/adapter-slog/main.go, cmd/examples/adapter-zap/main.go, cmd/examples/adapter-zerolog/main.go
Replaced /health endpoints with richer /users/{id} handlers featuring context enrichment (router, event_attached, user/request metadata), debug-level control via query params, error simulation, and port updates (8091→8101, 8092→8102, 8093→8103). Added Config.Message field to slog adapter.
Router Examples
cmd/examples/router-std/main.go, cmd/examples/router-gin/main.go, cmd/examples/router-echo/main.go, cmd/examples/router-fiber/main.go, cmd/examples/router-fiberv3/main.go
Refactored /users/{id} handlers with consistent pattern: path parameter extraction, structured context enrichment (router, event_attached, user/request metadata), SetRoute and debug-level controls, error injection via query params, and port updates (8101→8104, 8102→8105, 8103→8106, 8104→8107, 8105→8108).
Sampling Examples
cmd/examples/sampling-inbuilt/main.go, cmd/examples/sampling-custom/main.go
New HTTP servers demonstrating inbuilt and custom sampling middleware: rate limiting, error keeping, path-prefix filtering, slow-request detection, and error simulation; ports 8109–8110.
Event Accessor Functions
event_access.go
Added three new exported helper functions: EventFields (returns deep-copied field snapshot), EventHasError (checks error presence), and EventStartTime (returns start time), each with nil-safety checks.
Sampling Framework
sampling.go
Introduced composable sampling middleware system: SampleInput struct, Sampler and SamplerMiddleware types, ChainSampler composition, NeverSampler/AlwaysSampler base samplers, and middleware creators (KeepErrors, KeepSlowerThan, KeepPathPrefix, RateSampler) with deterministic pseudo-random selection.
Sampling Tests & Options
sampling_test.go, options.go
Added comprehensive test coverage for sampler chain composition, edge cases, and example usage; expanded SamplingRate field documentation with default/behavior notes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A sampler's quest through request streams so fine,
With chains of middlewares in elegant design,
From fiber to echo, from gin to the rest,
Context enriched—each handler's now blessed! ✨
Events and samplers, composable delight,
Logging infrastructure shining bright! 🌟

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.04% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main changes: updates to sampling APIs, examples, and documentation assets align with the substantial additions of sampling.go, sampling_test.go, new example files, and README expansions.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/sampling-api-docs-refresh

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Fix all issues with AI agents
In `@cmd/examples/adapter-slog/main.go`:
- Line 17: Replace the placeholder message "Yooooo" in the hc.Config passed to
stdhappycontext.Middleware with a meaningful, descriptive message (for example
"request handled" or "http request") so the example is clear; locate the call
creating mw (mw := stdhappycontext.Middleware(hc.Config{Sink: sink,
SamplingRate: 0.1, Message: "Yooooo"})) and update the Message field to a
production-ready string.

In `@cmd/examples/adapter-zerolog/main.go`:
- Around line 20-36: The route string passed to hc.SetRoute does not match the
registered mux pattern; update the call to hc.SetRoute in the handler so it uses
the same pattern syntax as mux.HandleFunc (i.e., replace "/users/:id" with
"/users/{id}") so SetRoute and the registered route are consistent; locate the
handler registered with mux.HandleFunc("/users/{id}", ...) and change the
argument to hc.SetRoute accordingly.

In `@cmd/examples/sampling-custom/main.go`:
- Around line 28-30: The sampler uses hc.EventFields which calls e.snapshot(),
but event_access.go exposes incorrect accessor names so e.snapshot() doesn't
exist/compile; open event_access.go and rename or add the correct methods so the
Event type implements snapshot() (and any other expected accessors) with the
proper receiver and signature, rebuild to ensure hc.EventFields compiles and the
tier assertion in this file is valid; reference hc.EventFields, e.snapshot(),
and event_access.go while making the fixes.

In `@README.md`:
- Around line 121-342: The README "More Examples" inline snippets use port
values that differ from the runnable apps in cmd/examples (e.g., snippets "2.
gin + slog", "5. echo + slog", "6. net/http + zap", "7. net/http + zerolog" use
:8102, :8103, :8092, :8093 while cmd/examples uses :8105, :8106, :8092, :8093);
either unify the port numbers so the snippets match the corresponding
cmd/examples apps or add a clear one-line note above the examples stating that
the inline snippets are standalone and intentionally use different ports than
the cmd/examples directory, and update the snippet summaries (e.g., "2. gin +
slog", "3. fiber v2 + slog", etc.) to reference the chosen approach so readers
aren’t confused.
- Line 65: The call to http.ListenAndServe(":8080", mw(mux)) is placed outside
the func main() block; move or indent that line so it lives inside the main
function's braces and is properly indented, ensuring mw and mux are in scope
(i.e., place the ListenAndServe call within the body of func main where mux and
mw are defined and format with the same indentation style as surrounding
statements).
🧹 Nitpick comments (3)
cmd/examples/sampling-custom/main.go (1)

48-50: time.Sleep on the request goroutine is fine for a demo, but consider a brief inline comment.

A short comment like // simulate slow upstream call would clarify intent for users reading this example as reference material.

sampling.go (1)

69-81: Clamping negative minDuration to zero makes KeepSlowerThan keep all requests.

When minDuration is negative it is clamped to 0, but in.Duration >= 0 is always true for real-world request durations, so the middleware silently becomes an AlwaysSampler. Consider clamping to 0 and returning the passthrough (next) middleware instead, or documenting this edge-case more explicitly.

Suggested approach
 func KeepSlowerThan(minDuration time.Duration) SamplerMiddleware {
 	if minDuration < 0 {
 		minDuration = 0
 	}
+	if minDuration == 0 {
+		return func(next Sampler) Sampler { return next }
+	}
 	return func(next Sampler) Sampler {
 		return func(in SampleInput) bool {
 			return in.Duration >= minDuration || next(in)
 		}
 	}
 }
cmd/examples/sampling-inbuilt/main.go (1)

15-38: Example clearly demonstrates the composable sampling API.

Good showcase of ChainSampler with rate limiting, error retention, path-prefix, and latency-based sampling all wired together. The two routes effectively exercise different sampling paths.

One minor nit: _ = http.ListenAndServe(...) silently discards bind/listen errors. For examples, log.Fatal(http.ListenAndServe(...)) is more idiomatic and helps users debug port conflicts.

Optional tweak
-	_ = http.ListenAndServe(":8109", mw(mux))
+	log.Fatal(http.ListenAndServe(":8109", mw(mux)))

(requires adding "log" to imports)

Comment on lines +28 to +30
fields := hc.EventFields(in.Event)
tier, _ := fields["user_tier"].(string)
return tier == "enterprise"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

hc.EventFields depends on the broken accessors in event_access.go — this sampler won't work until that's fixed.

EventFields calls e.snapshot() which doesn't compile (see review on event_access.go). Once those method names are corrected, this usage will work correctly — the nil-map type assertion on Line 29 is safe.

🤖 Prompt for AI Agents
In `@cmd/examples/sampling-custom/main.go` around lines 28 - 30, The sampler uses
hc.EventFields which calls e.snapshot(), but event_access.go exposes incorrect
accessor names so e.snapshot() doesn't exist/compile; open event_access.go and
rename or add the correct methods so the Event type implements snapshot() (and
any other expected accessors) with the proper receiver and signature, rebuild to
ensure hc.EventFields compiles and the tier assertion in this file is valid;
reference hc.EventFields, e.snapshot(), and event_access.go while making the
fixes.

@spa5k spa5k merged commit d8a017f into main Feb 9, 2026
2 checks passed
@spa5k spa5k deleted the feat/sampling-api-docs-refresh branch February 9, 2026 19:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant