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)
|
|
|
|
if v != nil {
|
|
|
|
panic(fmt.Sprintf("telemetry logger already set in the context: %v", v))
|
2024-11-29 00:57:48 +00:00
|
|
|
}
|
|
|
|
|
2025-01-03 06:01:22 +00:00
|
|
|
return context.WithValue(ctx, telemetryLoggerKey, &defaultLogger{logs: []FrontendLog{}})
|
2024-11-29 00:57:48 +00:00
|
|
|
}
|
|
|
|
|
2025-01-03 06:01:22 +00:00
|
|
|
func WithMockLogger(ctx context.Context) context.Context {
|
|
|
|
v := ctx.Value(telemetryLoggerKey)
|
|
|
|
if v != nil {
|
|
|
|
panic(fmt.Sprintf("telemetry logger already set in the context: %v", v))
|
|
|
|
}
|
|
|
|
|
|
|
|
return context.WithValue(ctx, telemetryLoggerKey, &mockLogger{})
|
|
|
|
}
|
|
|
|
|
|
|
|
func fromContext(ctx context.Context) Logger {
|
|
|
|
v := ctx.Value(telemetryLoggerKey)
|
|
|
|
if v == nil {
|
2024-11-29 00:57:48 +00:00
|
|
|
panic("telemetry logger not found in the context")
|
|
|
|
}
|
2025-01-03 06:01:22 +00:00
|
|
|
|
|
|
|
switch v.(type) {
|
|
|
|
case *defaultLogger:
|
|
|
|
return v.(*defaultLogger)
|
|
|
|
case *mockLogger:
|
|
|
|
return v.(*mockLogger)
|
|
|
|
default:
|
|
|
|
panic(fmt.Sprintf("unexpected telemetry logger type: %T", v))
|
|
|
|
}
|
2024-11-29 00:57:48 +00:00
|
|
|
}
|