2024-11-29 00:57:48 +00:00
|
|
|
package telemetry
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2025-01-03 06:01:22 +00:00
|
|
|
"fmt"
|
2024-11-29 00:57:48 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Private type to store the telemetry logger in the context
|
|
|
|
type telemetryLogger int
|
|
|
|
|
|
|
|
// Key to store the telemetry logger in the context
|
|
|
|
var telemetryLoggerKey telemetryLogger
|
|
|
|
|
2025-01-03 06:01:22 +00:00
|
|
|
func WithDefaultLogger(ctx context.Context) context.Context {
|
|
|
|
v := ctx.Value(telemetryLoggerKey)
|
2025-01-03 06:17:45 +00:00
|
|
|
|
|
|
|
// If no logger is set in the context, set the default logger.
|
|
|
|
if v == nil {
|
2025-01-03 06:38:09 +00:00
|
|
|
nctx := context.WithValue(ctx, telemetryLoggerKey, &defaultLogger{})
|
2025-01-03 06:17:45 +00:00
|
|
|
return nctx
|
|
|
|
}
|
|
|
|
|
|
|
|
switch v.(type) {
|
|
|
|
case *defaultLogger:
|
2025-01-03 06:38:09 +00:00
|
|
|
panic(fmt.Errorf("default telemetry logger already set in the context: %T", v))
|
2025-01-03 06:17:45 +00:00
|
|
|
case *mockLogger:
|
|
|
|
// Do nothing. Unit and integration tests set the mock logger in the context
|
|
|
|
// to avoid making actual API calls. Thus WithDefaultLogger should silently
|
|
|
|
// ignore the mock logger.
|
|
|
|
default:
|
2025-01-03 06:38:09 +00:00
|
|
|
panic(fmt.Errorf("unexpected telemetry logger type: %T", v))
|
2024-11-29 00:57:48 +00:00
|
|
|
}
|
|
|
|
|
2025-01-03 06:17:45 +00:00
|
|
|
return ctx
|
2024-11-29 00:57:48 +00:00
|
|
|
}
|
|
|
|
|
2025-01-03 06:17:45 +00:00
|
|
|
// WithMockLogger sets a mock telemetry logger in the context. It overrides the
|
|
|
|
// default logger if it is already set in the context.
|
2025-01-03 06:01:22 +00:00
|
|
|
func WithMockLogger(ctx context.Context) context.Context {
|
|
|
|
v := ctx.Value(telemetryLoggerKey)
|
|
|
|
if v != nil {
|
2025-01-03 06:38:09 +00:00
|
|
|
panic(fmt.Errorf("telemetry logger already set in the context: %T", v))
|
2025-01-03 06:01:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return context.WithValue(ctx, telemetryLoggerKey, &mockLogger{})
|
|
|
|
}
|
|
|
|
|
|
|
|
func fromContext(ctx context.Context) Logger {
|
|
|
|
v := ctx.Value(telemetryLoggerKey)
|
|
|
|
if v == nil {
|
2025-01-03 06:38:09 +00:00
|
|
|
panic(fmt.Errorf("telemetry logger not found in the context"))
|
2024-11-29 00:57:48 +00:00
|
|
|
}
|
2025-01-03 06:01:22 +00:00
|
|
|
|
2025-01-03 06:17:45 +00:00
|
|
|
switch vv := v.(type) {
|
2025-01-03 06:01:22 +00:00
|
|
|
case *defaultLogger:
|
2025-01-03 06:17:45 +00:00
|
|
|
return vv
|
2025-01-03 06:01:22 +00:00
|
|
|
case *mockLogger:
|
2025-01-03 06:17:45 +00:00
|
|
|
return vv
|
2025-01-03 06:01:22 +00:00
|
|
|
default:
|
2025-01-03 06:38:09 +00:00
|
|
|
panic(fmt.Errorf("unexpected telemetry logger type: %T", v))
|
2025-01-03 06:01:22 +00:00
|
|
|
}
|
2024-11-29 00:57:48 +00:00
|
|
|
}
|