databricks-cli/libs/telemetry/context.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

63 lines
1.6 KiB
Go
Raw Permalink Normal View History

2024-11-29 00:57:48 +00:00
package telemetry
import (
"context"
"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
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.
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))
}
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:17:45 +00:00
switch vv := v.(type) {
case *defaultLogger:
2025-01-03 06:17:45 +00:00
return vv
case *mockLogger:
2025-01-03 06:17:45 +00:00
return vv
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
}