-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathobservability_options.go
More file actions
360 lines (333 loc) · 11 KB
/
observability_options.go
File metadata and controls
360 lines (333 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// Copyright 2025 The Rivaas Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app
import (
"fmt"
"regexp"
"time"
"rivaas.dev/logging"
"rivaas.dev/metrics"
"rivaas.dev/tracing"
stderrors "errors"
)
// AccessLogScope controls which HTTP requests are logged as access logs.
// When unset, production defaults to AccessLogScopeErrorsOnly and development to AccessLogScopeAll.
type AccessLogScope string
const (
// AccessLogScopeAll logs every request (including 2xx). Use in production only if you need full request logs.
AccessLogScopeAll AccessLogScope = "all"
// AccessLogScopeErrorsOnly logs only errors (status >= 400) and slow requests. Reduces log volume.
AccessLogScopeErrorsOnly AccessLogScope = "errors_only"
)
// ObservabilityOption configures unified observability settings.
// These options configure metrics, tracing, logging, and shared settings like path exclusions.
type ObservabilityOption func(*observabilitySettings)
// loggingConfig holds logging configuration settings.
type loggingConfig struct {
enabled bool
options []logging.Option
}
// observabilitySettings holds unified observability configuration.
type observabilitySettings struct {
// Component configurations
metrics *metricsConfig
tracing *tracingConfig
logging *loggingConfig
// Metrics server configuration (mutually exclusive)
metricsOnMainRouter bool // If true, mount metrics on main router
metricsMainRouterPath string // Path on main router (default: /metrics)
metricsSeparateServer bool // If true, use custom separate server config
metricsSeparateAddr string // Address for separate server (e.g., ":9091")
metricsSeparatePath string // Path on separate server (default: /metrics)
// Shared settings
pathFilter *pathFilter
accessLogging bool
accessLogScope *AccessLogScope // nil means use environment default (production => errors_only, development => all)
slowThreshold time.Duration
// Validation errors collected during option application
validationErrors []error
}
// defaultObservabilitySettings creates observability settings with sensible defaults.
func defaultObservabilitySettings() *observabilitySettings {
return &observabilitySettings{
pathFilter: newPathFilterWithDefaults(),
accessLogging: true,
slowThreshold: time.Second,
}
}
// WithMetrics enables metrics collection with the given options.
// Service name and version are automatically injected from app-level configuration.
//
// Example:
//
// app.MustNew(
// app.WithServiceName("orders-api"),
// app.WithObservability(
// app.WithMetrics(), // Prometheus is default
// ),
// )
func WithMetrics(opts ...metrics.Option) ObservabilityOption {
return func(s *observabilitySettings) {
s.metrics = &metricsConfig{
enabled: true,
options: opts,
}
}
}
// WithTracing enables distributed tracing with the given options.
// Service name and version are automatically injected from app-level configuration.
//
// Example:
//
// app.MustNew(
// app.WithServiceName("orders-api"),
// app.WithObservability(
// app.WithTracing(tracing.WithOTLP("localhost:4317")),
// ),
// )
func WithTracing(opts ...tracing.Option) ObservabilityOption {
return func(s *observabilitySettings) {
s.tracing = &tracingConfig{
enabled: true,
options: opts,
}
}
}
// WithLogging enables structured logging with the given options.
// Service name and version are automatically injected from app-level configuration.
//
// If not provided, a no-op logger is used (logs are discarded).
//
// The app automatically derives request-scoped loggers that include:
// - HTTP metadata (method, route, target path, client IP)
// - Request ID (if X-Request-ID header is present)
// - Trace/span IDs (if OpenTelemetry tracing is enabled)
//
// Example:
//
// app.MustNew(
// app.WithServiceName("orders-api"),
// app.WithServiceVersion("v1.0.0"),
// app.WithObservability(
// app.WithLogging(
// logging.WithJSONHandler(),
// logging.WithDebugLevel(),
// // Service name/version auto-injected from app config
// ),
// ),
// )
func WithLogging(opts ...logging.Option) ObservabilityOption {
return func(s *observabilitySettings) {
s.logging = &loggingConfig{
enabled: true,
options: opts,
}
}
}
// WithMetricsOnMainRouter mounts the metrics endpoint on the main application router
// instead of running a separate metrics server.
//
// By default, the metrics package runs a separate server on :9090.
// Use this option when you need metrics on the same port as the application,
// such as in Kubernetes environments with strict ingress rules.
//
// The separate metrics server is automatically disabled when this option is used.
//
// Example:
//
// app.MustNew(
// app.WithServiceName("orders-api"),
// app.WithObservability(
// app.WithMetrics(), // Prometheus is default
// app.WithMetricsOnMainRouter("/metrics"),
// ),
// )
func WithMetricsOnMainRouter(path string) ObservabilityOption {
return func(s *observabilitySettings) {
// Check for conflict
if s.metricsSeparateServer {
s.validationErrors = append(s.validationErrors,
stderrors.New("WithMetricsOnMainRouter and WithMetricsSeparateServer are mutually exclusive; use only one to configure where metrics are served"))
}
s.metricsOnMainRouter = true
if path == "" {
path = "/metrics"
}
s.metricsMainRouterPath = path
}
}
// WithMetricsSeparateServer configures the separate metrics server with custom address and path.
//
// By default, metrics run on a separate server at :9090/metrics.
// Use this option to customize the port or endpoint path.
//
// This is mutually exclusive with WithMetricsOnMainRouter.
//
// Example:
//
// app.MustNew(
// app.WithServiceName("orders-api"),
// app.WithObservability(
// app.WithMetrics(), // Prometheus is default
// app.WithMetricsSeparateServer(":9091", "/custom-metrics"),
// ),
// )
func WithMetricsSeparateServer(addr, path string) ObservabilityOption {
return func(s *observabilitySettings) {
// Check for conflict
if s.metricsOnMainRouter {
s.validationErrors = append(s.validationErrors,
stderrors.New("WithMetricsOnMainRouter and WithMetricsSeparateServer are mutually exclusive; use only one to configure where metrics are served"))
}
s.metricsSeparateServer = true
s.metricsSeparateAddr = addr
if path == "" {
path = "/metrics"
}
s.metricsSeparatePath = path
}
}
// WithoutDefaultExclusions clears the default path exclusions.
// By default, common health/probe paths are excluded (/health, /livez, /ready, etc.).
// Use this option to start with an empty exclusion list, then add your own paths.
//
// Example:
//
// app.WithObservability(
// app.WithoutDefaultExclusions(),
// app.WithExcludePaths("/only-this", "/and-that"),
// )
func WithoutDefaultExclusions() ObservabilityOption {
return func(s *observabilitySettings) {
s.pathFilter = newPathFilter()
}
}
// WithExcludePaths adds exact paths to exclude from ALL observability
// (metrics, tracing, access logging).
// Multiple calls accumulate paths. Default exclusions are preserved unless
// WithoutDefaultExclusions() is called first.
//
// Example:
//
// app.WithObservability(
// app.WithExcludePaths("/custom-health", "/k8s-probe"),
// )
func WithExcludePaths(paths ...string) ObservabilityOption {
return func(s *observabilitySettings) {
if s.pathFilter == nil {
s.pathFilter = newPathFilterWithDefaults()
}
s.pathFilter.addPaths(paths...)
}
}
// WithExcludePrefixes adds path prefixes to exclude from ALL observability.
// Paths starting with any of these prefixes will be excluded.
//
// Example:
//
// app.WithObservability(
// app.WithExcludePrefixes("/internal/", "/admin/", "/debug/"),
// )
func WithExcludePrefixes(prefixes ...string) ObservabilityOption {
return func(s *observabilitySettings) {
if s.pathFilter == nil {
s.pathFilter = newPathFilterWithDefaults()
}
s.pathFilter.addPrefixes(prefixes...)
}
}
// WithExcludePatterns adds regex patterns to exclude from ALL observability.
// Paths matching any pattern will be excluded.
//
// Example:
//
// app.WithObservability(
// app.WithExcludePatterns(`^/v[0-9]+/internal/.*`, `^/debug/.*`),
// )
func WithExcludePatterns(patterns ...string) ObservabilityOption {
return func(s *observabilitySettings) {
if s.pathFilter == nil {
s.pathFilter = newPathFilterWithDefaults()
}
for _, pattern := range patterns {
compiled, err := regexp.Compile(pattern)
if err != nil {
if s.validationErrors == nil {
s.validationErrors = make([]error, 0, 1)
}
s.validationErrors = append(s.validationErrors,
fmt.Errorf("invalid regex pattern for path exclusion %q: %w", pattern, err))
continue
}
s.pathFilter.addPatterns(compiled)
}
}
}
// WithAccessLogging enables or disables access logging.
// Default is true.
//
// Example:
//
// app.WithObservability(
// app.WithAccessLogging(false), // Disable access logs
// )
func WithAccessLogging(enabled bool) ObservabilityOption {
return func(s *observabilitySettings) {
s.accessLogging = enabled
}
}
// WithAccessLogScope sets which requests are logged. When not set, production defaults to
// errors-only and development to all requests. Invalid scope values cause validation to fail at startup.
//
// Example:
//
// app.WithObservability(
// app.WithAccessLogScope(app.AccessLogScopeErrorsOnly),
// )
func WithAccessLogScope(scope AccessLogScope) ObservabilityOption {
return func(s *observabilitySettings) {
switch scope {
case AccessLogScopeAll, AccessLogScopeErrorsOnly:
s.accessLogScope = &scope
default:
if s.validationErrors == nil {
s.validationErrors = make([]error, 0, 1)
}
s.validationErrors = append(s.validationErrors,
fmt.Errorf("invalid access log scope %q: must be %q or %q", scope, AccessLogScopeAll, AccessLogScopeErrorsOnly))
}
}
}
// effectiveLogErrorsOnly returns the effective value for the observability recorder.
// Used when building the recorder; unset scope uses environment default.
func effectiveLogErrorsOnly(s *observabilitySettings, isProduction bool) bool {
if s.accessLogScope != nil {
return *s.accessLogScope == AccessLogScopeErrorsOnly
}
return isProduction
}
// WithSlowThreshold sets the duration threshold for marking requests as "slow".
// Slow requests are always logged, even when using AccessLogScopeErrorsOnly.
// Default is 1 second.
//
// Example:
//
// app.WithObservability(
// app.WithSlowThreshold(500 * time.Millisecond),
// )
func WithSlowThreshold(d time.Duration) ObservabilityOption {
return func(s *observabilitySettings) {
s.slowThreshold = d
}
}