diff --git a/MODULE.bazel b/MODULE.bazel index 06b583f1a2..70fa10b9d7 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -39,7 +39,6 @@ use_repo( "com_github_go_sql_driver_mysql", "com_github_google_go_containerregistry", "com_github_google_go_containerregistry_pkg_authn_k8schain", - "com_github_lmittmann_tint", "com_github_maypok86_otter", "com_github_moby_buildkit", "com_github_oapi_codegen_nullable", diff --git a/cmd/api/main.go b/cmd/api/main.go index 717c6db8bd..f238b9e249 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -2,6 +2,7 @@ package api import ( "context" + "time" "github.com/unkeyed/unkey/pkg/cli" "github.com/unkeyed/unkey/pkg/clock" @@ -111,6 +112,12 @@ var Cmd = &cli.Command{ cli.Int64("max-request-body-size", "Maximum allowed request body size in bytes. Set to 0 or negative to disable limit. Default: 10485760 (10MB)", cli.Default(int64(10485760)), cli.EnvVar("UNKEY_MAX_REQUEST_BODY_SIZE")), + // Logging Sampler Configuration + cli.Float("log-sample-rate", "Baseline probability (0.0-1.0) of emitting log events. Default: 1.0", + cli.Default(1.0), cli.EnvVar("UNKEY_LOG_SAMPLE_RATE")), + cli.Duration("log-slow-threshold", "Duration threshold for slow event sampling. Default: 1s", + cli.Default(time.Second), cli.EnvVar("UNKEY_LOG_SLOW_THRESHOLD")), + // CTRL Service Configuration cli.String("ctrl-url", "CTRL service connection URL for deployment management. Example: http://ctrl:7091", cli.EnvVar("UNKEY_CTRL_URL")), @@ -203,6 +210,9 @@ func action(ctx context.Context, cmd *cli.Command) error { // Request body configuration MaxRequestBodySize: cmd.Int64("max-request-body-size"), + // Logging sampler configuration + LogSampleRate: cmd.Float("log-sample-rate"), + LogSlowThreshold: cmd.Duration("log-slow-threshold"), } err := config.Validate() diff --git a/cmd/deploy/BUILD.bazel b/cmd/deploy/BUILD.bazel index d683d6b1e2..9ccd64d661 100644 --- a/cmd/deploy/BUILD.bazel +++ b/cmd/deploy/BUILD.bazel @@ -12,7 +12,7 @@ go_library( "//cmd/deploy/internal/ui", "//pkg/cli", "//pkg/git", - "//pkg/otel/logging", + "//pkg/logger", "@com_github_unkeyed_sdks_api_go_v2//:go", "@com_github_unkeyed_sdks_api_go_v2//models/components", "@org_golang_x_text//cases", diff --git a/cmd/deploy/control_plane.go b/cmd/deploy/control_plane.go index 30df92ea34..34536d1b2a 100644 --- a/cmd/deploy/control_plane.go +++ b/cmd/deploy/control_plane.go @@ -8,7 +8,7 @@ import ( unkey "github.com/unkeyed/sdks/api/go/v2" "github.com/unkeyed/sdks/api/go/v2/models/components" "github.com/unkeyed/unkey/pkg/git" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) // DeploymentStatusEvent represents a status change event @@ -117,7 +117,6 @@ func (c *ControlPlaneClient) GetDeployment(ctx context.Context, deploymentID str // PollDeploymentStatus polls for deployment changes and calls event handlers func (c *ControlPlaneClient) PollDeploymentStatus( ctx context.Context, - logger logging.Logger, deploymentID string, onStatusChange func(DeploymentStatusEvent) error, ) error { diff --git a/cmd/deploy/main.go b/cmd/deploy/main.go index f93b80da1b..0df57f34a6 100644 --- a/cmd/deploy/main.go +++ b/cmd/deploy/main.go @@ -9,7 +9,6 @@ import ( "github.com/unkeyed/unkey/cmd/deploy/internal/ui" "github.com/unkeyed/unkey/pkg/cli" "github.com/unkeyed/unkey/pkg/git" - "github.com/unkeyed/unkey/pkg/otel/logging" "golang.org/x/text/cases" "golang.org/x/text/language" ) @@ -103,7 +102,6 @@ func DeployAction(ctx context.Context, cmd *cli.Command) error { func executeDeploy(ctx context.Context, opts DeployOptions) error { terminal := ui.NewUI() - logger := logging.New() gitInfo := git.GetInfo() // Auto-detect branch and commit from git if not specified @@ -151,7 +149,7 @@ func executeDeploy(ctx context.Context, opts DeployOptions) error { } // Poll for deployment completion - err = controlPlane.PollDeploymentStatus(ctx, logger, deploymentID, onStatusChange) + err = controlPlane.PollDeploymentStatus(ctx, deploymentID, onStatusChange) if err != nil { terminal.StopSpinner("Deployment failed", false) return err diff --git a/cmd/dev/seed/BUILD.bazel b/cmd/dev/seed/BUILD.bazel index 585dc843e3..9b7f8ae92e 100644 --- a/cmd/dev/seed/BUILD.bazel +++ b/cmd/dev/seed/BUILD.bazel @@ -18,7 +18,7 @@ go_library( "//pkg/clickhouse/schema", "//pkg/db", "//pkg/db/types", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/uid", ], ) diff --git a/cmd/dev/seed/local.go b/cmd/dev/seed/local.go index e01e406fb6..0a5bfd7ccb 100644 --- a/cmd/dev/seed/local.go +++ b/cmd/dev/seed/local.go @@ -14,7 +14,7 @@ import ( "github.com/unkeyed/unkey/pkg/cli" "github.com/unkeyed/unkey/pkg/db" dbtype "github.com/unkeyed/unkey/pkg/db/types" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/uid" ) @@ -33,19 +33,15 @@ var localCmd = &cli.Command{ } func seedLocal(ctx context.Context, cmd *cli.Command) error { - logger := logging.New() - database, err := db.New(db.Config{ PrimaryDSN: cmd.RequireString("database-primary"), ReadOnlyDSN: "", - Logger: logger, }) if err != nil { return fmt.Errorf("failed to connect to MySQL: %w", err) } keyService, err := keys.New(keys.Config{ - Logger: logger, DB: database, RateLimiter: nil, RBAC: nil, diff --git a/cmd/dev/seed/sentinel.go b/cmd/dev/seed/sentinel.go index 119cd7ae72..840755f087 100644 --- a/cmd/dev/seed/sentinel.go +++ b/cmd/dev/seed/sentinel.go @@ -12,7 +12,6 @@ import ( "github.com/unkeyed/unkey/pkg/clickhouse" "github.com/unkeyed/unkey/pkg/clickhouse/schema" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/uid" ) @@ -30,13 +29,10 @@ var sentinelCmd = &cli.Command{ } func seedSentinel(ctx context.Context, cmd *cli.Command) error { - logger := logging.New() - // Connect to MySQL database, err := db.New(db.Config{ PrimaryDSN: cmd.RequireString("database-primary"), ReadOnlyDSN: "", - Logger: logger, }) if err != nil { return fmt.Errorf("failed to connect to MySQL: %w", err) @@ -44,8 +40,7 @@ func seedSentinel(ctx context.Context, cmd *cli.Command) error { // Connect to ClickHouse ch, err := clickhouse.New(clickhouse.Config{ - URL: cmd.String("clickhouse-url"), - Logger: logger, + URL: cmd.String("clickhouse-url"), }) if err != nil { return fmt.Errorf("failed to connect to ClickHouse: %w", err) @@ -67,7 +62,6 @@ func seedSentinel(ctx context.Context, cmd *cli.Command) error { numRequests: cmd.RequireInt("num-requests"), db: database, clickhouse: ch, - logger: logger, } return seeder.Seed(ctx) @@ -78,7 +72,6 @@ type SentinelSeeder struct { numRequests int db db.Database clickhouse clickhouse.ClickHouse - logger logging.Logger } func (s *SentinelSeeder) Seed(ctx context.Context) error { diff --git a/cmd/dev/seed/verifications.go b/cmd/dev/seed/verifications.go index 0d6aaf7592..f8399f7727 100644 --- a/cmd/dev/seed/verifications.go +++ b/cmd/dev/seed/verifications.go @@ -16,7 +16,6 @@ import ( "github.com/unkeyed/unkey/pkg/clickhouse" "github.com/unkeyed/unkey/pkg/clickhouse/schema" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/uid" ) @@ -40,13 +39,10 @@ var verificationsCmd = &cli.Command{ const chunkSize = 50_000 func seedVerifications(ctx context.Context, cmd *cli.Command) error { - logger := logging.New() - // Connect to MySQL database, err := db.New(db.Config{ PrimaryDSN: cmd.RequireString("database-primary"), ReadOnlyDSN: "", - Logger: logger, }) if err != nil { return fmt.Errorf("failed to connect to MySQL: %w", err) @@ -54,8 +50,7 @@ func seedVerifications(ctx context.Context, cmd *cli.Command) error { // Connect to ClickHouse ch, err := clickhouse.New(clickhouse.Config{ - URL: cmd.String("clickhouse-url"), - Logger: logger, + URL: cmd.String("clickhouse-url"), }) if err != nil { return fmt.Errorf("failed to connect to ClickHouse: %w", err) @@ -63,7 +58,6 @@ func seedVerifications(ctx context.Context, cmd *cli.Command) error { // Create key service for proper key generation keyService, err := keys.New(keys.Config{ - Logger: logger, DB: database, RateLimiter: nil, RBAC: nil, diff --git a/cmd/frontline/main.go b/cmd/frontline/main.go index e6a7436fe3..7023a1aeda 100644 --- a/cmd/frontline/main.go +++ b/cmd/frontline/main.go @@ -2,6 +2,7 @@ package frontline import ( "context" + "time" "github.com/unkeyed/unkey/pkg/cli" "github.com/unkeyed/unkey/pkg/uid" @@ -73,6 +74,12 @@ var Cmd = &cli.Command{ cli.String("ctrl-addr", "Address of the control plane", cli.Default("localhost:8080"), cli.EnvVar("UNKEY_CTRL_ADDR")), + + // Logging Sampler Configuration + cli.Float("log-sample-rate", "Baseline probability (0.0-1.0) of emitting log events. Default: 1.0", + cli.Default(1.0), cli.EnvVar("UNKEY_LOG_SAMPLE_RATE")), + cli.Duration("log-slow-threshold", "Duration threshold for slow event sampling. Default: 1s", + cli.Default(time.Second), cli.EnvVar("UNKEY_LOG_SLOW_THRESHOLD")), }, Action: action, } @@ -110,6 +117,10 @@ func action(ctx context.Context, cmd *cli.Command) error { // Vault configuration VaultURL: cmd.String("vault-url"), VaultToken: cmd.String("vault-token"), + + // Logging sampler configuration + LogSampleRate: cmd.Float("log-sample-rate"), + LogSlowThreshold: cmd.Duration("log-slow-threshold"), } err := config.Validate() diff --git a/cmd/inject/BUILD.bazel b/cmd/inject/BUILD.bazel index cca56060b6..aefaa587e3 100644 --- a/cmd/inject/BUILD.bazel +++ b/cmd/inject/BUILD.bazel @@ -13,7 +13,7 @@ go_library( deps = [ "//pkg/assert", "//pkg/cli", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/secrets/provider", ], ) diff --git a/cmd/inject/run.go b/cmd/inject/run.go index 9583248bf2..08c8d6e724 100644 --- a/cmd/inject/run.go +++ b/cmd/inject/run.go @@ -10,7 +10,7 @@ import ( "syscall" "time" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/secrets/provider" ) @@ -19,8 +19,6 @@ func run(ctx context.Context, cfg config) error { return fmt.Errorf("no command specified") } - logger := logging.New() - // Clear sensitive UNKEY_* env vars first, before setting user secrets. // This prevents leaking config like UNKEY_TOKEN to the child process, // while allowing users to have secrets named UNKEY_* if they want. @@ -46,7 +44,7 @@ func run(ctx context.Context, cfg config) error { } } - return execCommand(cfg.Args, logger) + return execCommand(cfg.Args) } func fetchSecrets(ctx context.Context, cfg config) (map[string]string, error) { @@ -101,7 +99,7 @@ func clearSensitiveEnvVars() error { return nil } -func execCommand(args []string, logger logging.Logger) error { +func execCommand(args []string) error { binary, err := exec.LookPath(args[0]) if err != nil { return fmt.Errorf("command not found: %s: %w", args[0], err) diff --git a/cmd/krane/main.go b/cmd/krane/main.go index b1dc119f5a..2ea11683d3 100644 --- a/cmd/krane/main.go +++ b/cmd/krane/main.go @@ -2,6 +2,7 @@ package krane import ( "context" + "time" "github.com/unkeyed/unkey/pkg/cli" "github.com/unkeyed/unkey/pkg/uid" @@ -88,6 +89,12 @@ unkey run krane # Run with default configurati cli.Float("otel-trace-sampling-rate", "Sampling rate for traces (0.0 to 1.0)", cli.Default(0.01), cli.EnvVar("UNKEY_OTEL_TRACE_SAMPLING_RATE")), + + // Logging Sampler Configuration + cli.Float("log-sample-rate", "Baseline probability (0.0-1.0) of emitting log events. Default: 1.0", + cli.Default(1.0), cli.EnvVar("UNKEY_LOG_SAMPLE_RATE")), + cli.Duration("log-slow-threshold", "Duration threshold for slow event sampling. Default: 1s", + cli.Default(time.Second), cli.EnvVar("UNKEY_LOG_SLOW_THRESHOLD")), }, Action: action, } @@ -109,6 +116,10 @@ func action(ctx context.Context, cmd *cli.Command) error { ControlPlaneBearer: cmd.RequireString("control-plane-bearer"), OtelEnabled: cmd.Bool("otel-enabled"), OtelTraceSamplingRate: cmd.Float("otel-trace-sampling-rate"), + + // Logging sampler configuration + LogSampleRate: cmd.Float("log-sample-rate"), + LogSlowThreshold: cmd.Duration("log-slow-threshold"), } // Validate configuration diff --git a/cmd/preflight/main.go b/cmd/preflight/main.go index 57b8946e2c..b82a24456c 100644 --- a/cmd/preflight/main.go +++ b/cmd/preflight/main.go @@ -2,6 +2,7 @@ package preflight import ( "context" + "time" "github.com/unkeyed/unkey/pkg/cli" "github.com/unkeyed/unkey/svc/preflight" @@ -31,6 +32,11 @@ var Cmd = &cli.Command{ cli.EnvVar("UNKEY_INSECURE_REGISTRIES")), cli.StringSlice("registry-aliases", "Comma-separated list of registry aliases (from=to)", cli.EnvVar("UNKEY_REGISTRY_ALIASES")), + // Logging Sampler Configuration + cli.Float("log-sample-rate", "Baseline probability (0.0-1.0) of emitting log events. Default: 1.0", + cli.Default(1.0), cli.EnvVar("UNKEY_LOG_SAMPLE_RATE")), + cli.Duration("log-slow-threshold", "Duration threshold for slow event sampling. Default: 1s", + cli.Default(time.Second), cli.EnvVar("UNKEY_LOG_SLOW_THRESHOLD")), }, Action: action, } @@ -46,6 +52,9 @@ func action(ctx context.Context, cmd *cli.Command) error { DepotToken: cmd.String("depot-token"), InsecureRegistries: cmd.StringSlice("insecure-registries"), RegistryAliases: cmd.StringSlice("registry-aliases"), + // Logging sampler configuration + LogSampleRate: cmd.Float("log-sample-rate"), + LogSlowThreshold: cmd.Duration("log-slow-threshold"), } if err := config.Validate(); err != nil { diff --git a/cmd/sentinel/main.go b/cmd/sentinel/main.go index c2a9e034c4..db7341b6a2 100644 --- a/cmd/sentinel/main.go +++ b/cmd/sentinel/main.go @@ -2,6 +2,7 @@ package sentinel import ( "context" + "time" "github.com/unkeyed/unkey/pkg/cli" "github.com/unkeyed/unkey/pkg/uid" @@ -51,6 +52,12 @@ var Cmd = &cli.Command{ cli.Float("otel-trace-sampling-rate", "Sampling rate for OpenTelemetry traces (0.0-1.0). Default: 0.25", cli.Default(0.25), cli.EnvVar("UNKEY_OTEL_TRACE_SAMPLING_RATE")), cli.Int("prometheus-port", "Enable Prometheus /metrics endpoint on specified port. Set to 0 to disable.", cli.EnvVar("UNKEY_PROMETHEUS_PORT")), + + // Logging Sampler Configuration + cli.Float("log-sample-rate", "Baseline probability (0.0-1.0) of emitting log events. Default: 1.0", + cli.Default(1.0), cli.EnvVar("UNKEY_LOG_SAMPLE_RATE")), + cli.Duration("log-slow-threshold", "Duration threshold for slow event sampling. Default: 1s", + cli.Default(time.Second), cli.EnvVar("UNKEY_LOG_SLOW_THRESHOLD")), }, Action: action, } @@ -75,5 +82,9 @@ func action(ctx context.Context, cmd *cli.Command) error { OtelEnabled: cmd.Bool("otel"), OtelTraceSamplingRate: cmd.Float("otel-trace-sampling-rate"), PrometheusPort: cmd.Int("prometheus-port"), + + // Logging sampler configuration + LogSampleRate: cmd.Float("log-sample-rate"), + LogSlowThreshold: cmd.Duration("log-slow-threshold"), }) } diff --git a/cmd/vault/main.go b/cmd/vault/main.go index 82c5ecfc04..235953ddfe 100644 --- a/cmd/vault/main.go +++ b/cmd/vault/main.go @@ -2,6 +2,7 @@ package vault import ( "context" + "time" "github.com/unkeyed/unkey/pkg/cli" "github.com/unkeyed/unkey/pkg/uid" @@ -55,6 +56,12 @@ var Cmd = &cli.Command{ cli.EnvVar("UNKEY_OTEL_TRACE_SAMPLING_RATE")), cli.String("region", "Cloud region identifier", cli.EnvVar("UNKEY_REGION")), + + // Logging Sampler Configuration + cli.Float("log-sample-rate", "Baseline probability (0.0-1.0) of emitting log events. Default: 1.0", + cli.Default(1.0), cli.EnvVar("UNKEY_LOG_SAMPLE_RATE")), + cli.Duration("log-slow-threshold", "Duration threshold for slow event sampling. Default: 1s", + cli.Default(time.Second), cli.EnvVar("UNKEY_LOG_SLOW_THRESHOLD")), }, Action: action, } @@ -76,6 +83,10 @@ func action(ctx context.Context, cmd *cli.Command) error { OtelEnabled: cmd.Bool("otel-enabled"), OtelTraceSamplingRate: cmd.Float("otel-trace-sampling-rate"), Region: cmd.String("region"), + + // Logging sampler configuration + LogSampleRate: cmd.Float("log-sample-rate"), + LogSlowThreshold: cmd.Duration("log-slow-threshold"), } err := config.Validate() diff --git a/go.mod b/go.mod index 9da5c6d65a..2bc234b055 100644 --- a/go.mod +++ b/go.mod @@ -54,7 +54,6 @@ require ( github.com/google/go-containerregistry/pkg/authn/k8schain v0.0.0-20260114192324-795787c558e1 github.com/gordonklaus/ineffassign v0.2.0 github.com/kisielk/errcheck v1.9.0 - github.com/lmittmann/tint v1.1.2 github.com/maypok86/otter v1.2.4 github.com/moby/buildkit v0.26.3 github.com/nishanths/exhaustive v0.12.0 diff --git a/go.sum b/go.sum index 3c4a76276d..3c2b30818f 100644 --- a/go.sum +++ b/go.sum @@ -461,8 +461,6 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= -github.com/lmittmann/tint v1.1.2 h1:2CQzrL6rslrsyjqLDwD11bZ5OpLBPU+g3G/r5LSfS8w= -github.com/lmittmann/tint v1.1.2/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE= github.com/lufia/plan9stats v0.0.0-20250827001030-24949be3fa54 h1:mFWunSatvkQQDhpdyuFAYwyAan3hzCuma+Pz8sqvOfg= github.com/lufia/plan9stats v0.0.0-20250827001030-24949be3fa54/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= github.com/mackerelio/go-osstat v0.2.6 h1:gs4U8BZeS1tjrL08tt5VUliVvSWP26Ai2Ob8Lr7f2i0= diff --git a/internal/services/analytics/BUILD.bazel b/internal/services/analytics/BUILD.bazel index 8796e8df40..780c21b94d 100644 --- a/internal/services/analytics/BUILD.bazel +++ b/internal/services/analytics/BUILD.bazel @@ -19,7 +19,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/vault", ], ) diff --git a/internal/services/analytics/service.go b/internal/services/analytics/service.go index a990b83ca5..28af72e062 100644 --- a/internal/services/analytics/service.go +++ b/internal/services/analytics/service.go @@ -14,7 +14,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/vault" ) @@ -23,7 +22,6 @@ type connectionManager struct { settingsCache cache.Cache[string, db.FindClickhouseWorkspaceSettingsByWorkspaceIDRow] connectionCache cache.Cache[string, clickhouse.ClickHouse] database db.Database - logger logging.Logger baseURL string vault *vault.Service } @@ -32,7 +30,6 @@ type connectionManager struct { type ConnectionManagerConfig struct { SettingsCache cache.Cache[string, db.FindClickhouseWorkspaceSettingsByWorkspaceIDRow] Database db.Database - Logger logging.Logger Clock clock.Clock BaseURL string // e.g., "http://clickhouse:8123/default" or "clickhouse://clickhouse:9000/default" Vault *vault.Service @@ -44,7 +41,6 @@ func NewConnectionManager(config ConnectionManagerConfig) (ConnectionManager, er assert.NotNilAndNotZero(config.Vault, "vault is required"), assert.NotNilAndNotZero(config.SettingsCache, "settings cache is required"), assert.NotNilAndNotZero(config.Database, "database is required"), - assert.NotNilAndNotZero(config.Logger, "logger is required"), assert.NotNilAndNotZero(config.Clock, "clock is required"), assert.NotNilAndNotZero(config.BaseURL, "base URL is required"), ) @@ -60,7 +56,6 @@ func NewConnectionManager(config ConnectionManagerConfig) (ConnectionManager, er // It's fine to keep a long cache time for this. Fresh: 24 * time.Hour, Stale: 24 * time.Hour, - Logger: config.Logger, MaxSize: 1_000, Resource: "clickhouse_analytics_connection", Clock: config.Clock, @@ -73,7 +68,6 @@ func NewConnectionManager(config ConnectionManagerConfig) (ConnectionManager, er settingsCache: config.SettingsCache, connectionCache: connectionCache, database: config.Database, - logger: config.Logger, baseURL: config.BaseURL, vault: config.Vault, }, nil @@ -159,8 +153,7 @@ func (m *connectionManager) createConnection(ctx context.Context, workspaceID st // Inject workspace credentials parsedURL.User = url.UserPassword(settings.ClickhouseWorkspaceSetting.Username, decrypted.GetPlaintext()) conn, err := clickhouse.New(clickhouse.Config{ - URL: parsedURL.String(), - Logger: m.logger, + URL: parsedURL.String(), }) if err != nil { return nil, db.FindClickhouseWorkspaceSettingsByWorkspaceIDRow{}, fault.Wrap(err, diff --git a/internal/services/auditlogs/BUILD.bazel b/internal/services/auditlogs/BUILD.bazel index 549d32d4d1..a7b4d62171 100644 --- a/internal/services/auditlogs/BUILD.bazel +++ b/internal/services/auditlogs/BUILD.bazel @@ -15,7 +15,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/uid", ], ) diff --git a/internal/services/auditlogs/service.go b/internal/services/auditlogs/service.go index 8b715a855c..c26f395e02 100644 --- a/internal/services/auditlogs/service.go +++ b/internal/services/auditlogs/service.go @@ -5,15 +5,13 @@ import ( "github.com/unkeyed/unkey/pkg/assert" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // service implements the AuditLogService interface, providing audit logging // functionality with database persistence and structured logging capabilities. // The service handles batch insertion of audit logs within transactional contexts. type service struct { - db db.Database - logger logging.Logger + db db.Database } var _ AuditLogService = (*service)(nil) @@ -21,8 +19,7 @@ var _ AuditLogService = (*service)(nil) // Config contains the dependencies required to initialize an audit log service. // Both fields are required for proper service operation. type Config struct { - DB db.Database // Database interface for audit log persistence - Logger logging.Logger // Structured logger for service operations and error reporting + DB db.Database // Database interface for audit log persistence } // New creates a new audit log service instance with the provided configuration. @@ -31,13 +28,11 @@ type Config struct { func New(cfg Config) (*service, error) { if err := assert.All( assert.NotNil(cfg.DB, "db is required"), - assert.NotNil(cfg.Logger, "logger is required"), ); err != nil { return nil, fmt.Errorf("invalid auditlogs service config: %w", err) } return &service{ - db: cfg.DB, - logger: cfg.Logger, + db: cfg.DB, }, nil } diff --git a/internal/services/caches/BUILD.bazel b/internal/services/caches/BUILD.bazel index 6508da3f91..e730a5079f 100644 --- a/internal/services/caches/BUILD.bazel +++ b/internal/services/caches/BUILD.bazel @@ -17,7 +17,6 @@ go_library( "//pkg/clock", "//pkg/db", "//pkg/eventstream", - "//pkg/otel/logging", "//pkg/uid", ], ) diff --git a/internal/services/caches/caches.go b/internal/services/caches/caches.go index 1b5a2eea5d..f69c4c2038 100644 --- a/internal/services/caches/caches.go +++ b/internal/services/caches/caches.go @@ -12,7 +12,6 @@ import ( "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/eventstream" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/uid" ) @@ -60,9 +59,6 @@ func (c *Caches) Close() error { // Config defines the configuration options for initializing caches. type Config struct { - // Logger is used for logging cache operations and errors. - Logger logging.Logger - // Clock provides time functionality, allowing easier testing. Clock clock.Clock @@ -119,7 +115,6 @@ func createCache[K comparable, V any]( LocalCache: localCache, Topic: config.CacheInvalidationTopic, Dispatcher: dispatcher, - Logger: config.Logger, NodeID: config.NodeID, KeyToString: keyToString, StringToKey: stringToKey, @@ -149,11 +144,9 @@ func createCache[K comparable, V any]( // // Example: // -// logger := logging.NewLogger() // clock := clock.RealClock{} // // caches, err := caches.New(caches.Config{ -// Logger: logger, // Clock: clock, // CacheInvalidationTopic: topic, // optional for distributed invalidation // }) @@ -182,7 +175,7 @@ func New(config Config) (Caches, error) { var dispatcher *clustering.InvalidationDispatcher if config.CacheInvalidationTopic != nil { var err error - dispatcher, err = clustering.NewInvalidationDispatcher(config.CacheInvalidationTopic, config.Logger) + dispatcher, err = clustering.NewInvalidationDispatcher(config.CacheInvalidationTopic) if err != nil { return Caches{}, err } @@ -195,7 +188,6 @@ func New(config Config) (Caches, error) { cache.Config[cache.ScopedKey, db.FindRatelimitNamespace]{ Fresh: time.Minute, Stale: 24 * time.Hour, - Logger: config.Logger, MaxSize: 1_000_000, Resource: "ratelimit_namespace", Clock: config.Clock, @@ -214,7 +206,6 @@ func New(config Config) (Caches, error) { cache.Config[string, db.CachedKeyData]{ Fresh: 10 * time.Second, Stale: 10 * time.Minute, - Logger: config.Logger, MaxSize: 1_000_000, Resource: "verification_key_by_hash", Clock: config.Clock, @@ -233,7 +224,6 @@ func New(config Config) (Caches, error) { cache.Config[cache.ScopedKey, db.FindLiveApiByIDRow]{ Fresh: 10 * time.Second, Stale: 24 * time.Hour, - Logger: config.Logger, MaxSize: 1_000_000, Resource: "live_api_by_id", Clock: config.Clock, @@ -251,7 +241,6 @@ func New(config Config) (Caches, error) { cache.Config[string, db.FindClickhouseWorkspaceSettingsByWorkspaceIDRow]{ Fresh: time.Minute, Stale: 24 * time.Hour, - Logger: config.Logger, MaxSize: 1_000_000, Resource: "clickhouse_setting", Clock: config.Clock, @@ -270,7 +259,6 @@ func New(config Config) (Caches, error) { cache.Config[cache.ScopedKey, db.FindKeyAuthsByKeyAuthIdsRow]{ Fresh: 10 * time.Minute, Stale: 24 * time.Hour, - Logger: config.Logger, MaxSize: 1_000_000, Resource: "key_auth_to_api_row", Clock: config.Clock, @@ -289,7 +277,6 @@ func New(config Config) (Caches, error) { cache.Config[cache.ScopedKey, db.FindKeyAuthsByIdsRow]{ Fresh: 10 * time.Minute, Stale: 24 * time.Hour, - Logger: config.Logger, MaxSize: 1_000_000, Resource: "api_to_key_auth_row", Clock: config.Clock, diff --git a/internal/services/keys/BUILD.bazel b/internal/services/keys/BUILD.bazel index 8f75896fb4..be47012de3 100644 --- a/internal/services/keys/BUILD.bazel +++ b/internal/services/keys/BUILD.bazel @@ -29,7 +29,7 @@ go_library( "//pkg/db", "//pkg/fault", "//pkg/hash", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/otel/tracing", "//pkg/prometheus/metrics", "//pkg/ptr", diff --git a/internal/services/keys/doc.go b/internal/services/keys/doc.go index 938d36c6f1..03a8e5abab 100644 --- a/internal/services/keys/doc.go +++ b/internal/services/keys/doc.go @@ -27,7 +27,6 @@ The verification system uses a flexible, option-based approach that supports: To create a new keys service: svc, err := keys.New(keys.Config{ - Logger: logger, DB: database, RateLimiter: rateLimiter, UsageLimiter: usageLimiter, diff --git a/internal/services/keys/get.go b/internal/services/keys/get.go index 3fe67b1107..7eff045047 100644 --- a/internal/services/keys/get.go +++ b/internal/services/keys/get.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "log/slog" "strings" "time" @@ -14,6 +15,7 @@ import ( "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" "github.com/unkeyed/unkey/pkg/hash" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" "github.com/unkeyed/unkey/pkg/zen" ) @@ -61,6 +63,11 @@ func (s *service) GetRootKey(ctx context.Context, sess *zen.Session) (*KeyVerifi key.AuthorizedWorkspaceID = key.Key.ForWorkspaceID.String sess.WorkspaceID = key.AuthorizedWorkspaceID + logger.Set(ctx, slog.Group("auth", + slog.String("workspace_id", key.AuthorizedWorkspaceID), + slog.String("root_key_id", key.Key.ID), + )) + return key, log, nil } @@ -149,7 +156,6 @@ func (s *service) Get(ctx context.Context, sess *zen.Session, sha256Hash string) session: sess, rBAC: s.rbac, region: s.region, - logger: s.logger, clickhouse: s.clickhouse, rateLimiter: s.rateLimiter, usageLimiter: s.usageLimiter, @@ -224,7 +230,6 @@ func (s *service) Get(ctx context.Context, sess *zen.Session, sha256Hash string) AuthorizedWorkspaceID: key.WorkspaceID, rBAC: s.rbac, session: sess, - logger: s.logger, region: s.region, message: "", isRootKey: key.ForWorkspaceID.Valid, diff --git a/internal/services/keys/service.go b/internal/services/keys/service.go index 7e5cf76762..d37524b4da 100644 --- a/internal/services/keys/service.go +++ b/internal/services/keys/service.go @@ -6,13 +6,11 @@ import ( "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/clickhouse" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" ) // Config holds the configuration for creating a new keys service instance. type Config struct { - Logger logging.Logger // Logger for service operations DB db.Database // Database connection RateLimiter ratelimit.Service // Rate limiting service RBAC *rbac.RBAC // Role-based access control @@ -24,7 +22,6 @@ type Config struct { } type service struct { - logger logging.Logger db db.Database rateLimiter ratelimit.Service usageLimiter usagelimiter.Service @@ -40,7 +37,6 @@ type service struct { func New(config Config) (*service, error) { return &service{ - logger: config.Logger, db: config.DB, rbac: config.RBAC, rateLimiter: config.RateLimiter, diff --git a/internal/services/keys/validation.go b/internal/services/keys/validation.go index c37ecfca29..3f1edeb7a1 100644 --- a/internal/services/keys/validation.go +++ b/internal/services/keys/validation.go @@ -11,6 +11,7 @@ import ( "github.com/unkeyed/unkey/internal/services/usagelimiter" "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" @@ -232,7 +233,7 @@ func (k *KeyVerifier) withRateLimits(ctx context.Context, specifiedLimits []open } if err != nil { - k.logger.Error("Failed to ratelimit", + logger.Error("Failed to ratelimit", "key_id", k.Key.ID, "error", err.Error(), ) diff --git a/internal/services/keys/verifier.go b/internal/services/keys/verifier.go index 9d1e7fd8f4..ebf6591ae1 100644 --- a/internal/services/keys/verifier.go +++ b/internal/services/keys/verifier.go @@ -9,7 +9,6 @@ import ( "github.com/unkeyed/unkey/pkg/clickhouse" "github.com/unkeyed/unkey/pkg/clickhouse/schema" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/prometheus/metrics" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" @@ -57,7 +56,6 @@ type KeyVerifier struct { usageLimiter usagelimiter.Service // Usage limiting service rBAC *rbac.RBAC // Role-based access control service clickhouse clickhouse.ClickHouse // Clickhouse for telemetry - logger logging.Logger // Logger for verification operations } // GetRatelimitConfigs returns the rate limit configurations diff --git a/internal/services/ratelimit/BUILD.bazel b/internal/services/ratelimit/BUILD.bazel index bdbf3bcb79..5e057c57e9 100644 --- a/internal/services/ratelimit/BUILD.bazel +++ b/internal/services/ratelimit/BUILD.bazel @@ -21,7 +21,7 @@ go_library( "//pkg/circuitbreaker", "//pkg/clock", "//pkg/counter", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/otel/tracing", "//pkg/prometheus/metrics", "//pkg/repeat", diff --git a/internal/services/ratelimit/doc.go b/internal/services/ratelimit/doc.go index 52e8e31d3f..352780d7c1 100644 --- a/internal/services/ratelimit/doc.go +++ b/internal/services/ratelimit/doc.go @@ -28,7 +28,6 @@ The sliding window implementation: To create a new rate limiting service: svc, err := ratelimit.New(ratelimit.Config{ - Logger: logger, Cluster: cluster, Clock: clock, }) diff --git a/internal/services/ratelimit/interface.go b/internal/services/ratelimit/interface.go index e03c9ec3c3..c25754ad0e 100644 --- a/internal/services/ratelimit/interface.go +++ b/internal/services/ratelimit/interface.go @@ -149,7 +149,7 @@ type RatelimitResponse struct { // // func LoggingMiddleware(logger Logger) Middleware { // return func(next Service) Service { -// return &loggingService{next: next, logger: logger} +// return &loggingService{next: next} // } // } type Middleware func(Service) Service diff --git a/internal/services/ratelimit/replay.go b/internal/services/ratelimit/replay.go index 4e4bd3c373..b4d8b68199 100644 --- a/internal/services/ratelimit/replay.go +++ b/internal/services/ratelimit/replay.go @@ -5,6 +5,7 @@ import ( "time" "github.com/unkeyed/unkey/pkg/assert" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" "github.com/unkeyed/unkey/pkg/prometheus/metrics" ) @@ -38,7 +39,7 @@ func (s *service) replayRequests() { for req := range s.replayBuffer.Consume() { err := s.syncWithOrigin(context.Background(), req) if err != nil { - s.logger.Error("failed to replay request", "error", err.Error()) + logger.Error("failed to replay request", "error", err.Error()) } } } diff --git a/internal/services/ratelimit/service.go b/internal/services/ratelimit/service.go index 453f7e1f1b..bf7d9e83a9 100644 --- a/internal/services/ratelimit/service.go +++ b/internal/services/ratelimit/service.go @@ -10,7 +10,7 @@ import ( "github.com/unkeyed/unkey/pkg/circuitbreaker" "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/counter" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" "github.com/unkeyed/unkey/pkg/prometheus/metrics" "go.opentelemetry.io/otel/attribute" @@ -30,9 +30,6 @@ type service struct { // clock provides time-related functionality, can be mocked for testing clock clock.Clock - // logger handles structured logging output - logger logging.Logger - // shutdownCh signals service shutdown shutdownCh chan struct{} @@ -57,7 +54,6 @@ type service struct { // Config holds configuration for creating a new rate limiting service. type Config struct { - Logger logging.Logger // Clock for time-related operations. If nil, uses system clock. Clock clock.Clock @@ -81,7 +77,6 @@ func New(config Config) (*service, error) { s := &service{ clock: config.Clock, - logger: config.Logger, shutdownCh: make(chan struct{}), bucketsMu: sync.RWMutex{}, buckets: make(map[string]*bucket), @@ -345,7 +340,7 @@ func (s *service) checkBucketWithLockHeld(ctx context.Context, req RatelimitRequ currentKey := counterKey(b.key(), currentWindow.sequence) res, err := s.counter.Get(ctx, currentKey) if err != nil { - s.logger.Error("unable to get counter value", + logger.Error("unable to get counter value", "key", currentKey, "error", err.Error(), ) @@ -359,7 +354,7 @@ func (s *service) checkBucketWithLockHeld(ctx context.Context, req RatelimitRequ previousKey := counterKey(b.key(), previousWindow.sequence) res, err := s.counter.Get(ctx, previousKey) if err != nil { - s.logger.Error("unable to get counter value", + logger.Error("unable to get counter value", "key", previousKey, "error", err.Error(), ) diff --git a/internal/services/usagelimiter/BUILD.bazel b/internal/services/usagelimiter/BUILD.bazel index 3ab28bd2dc..8da6213517 100644 --- a/internal/services/usagelimiter/BUILD.bazel +++ b/internal/services/usagelimiter/BUILD.bazel @@ -17,7 +17,7 @@ go_library( "//pkg/circuitbreaker", "//pkg/counter", "//pkg/db", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/otel/tracing", "//pkg/prometheus/metrics", "//pkg/repeat", diff --git a/internal/services/usagelimiter/redis.go b/internal/services/usagelimiter/redis.go index 5b4733dd3f..5479a928ce 100644 --- a/internal/services/usagelimiter/redis.go +++ b/internal/services/usagelimiter/redis.go @@ -11,7 +11,7 @@ import ( "github.com/unkeyed/unkey/pkg/circuitbreaker" "github.com/unkeyed/unkey/pkg/counter" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" "github.com/unkeyed/unkey/pkg/prometheus/metrics" "github.com/unkeyed/unkey/pkg/repeat" @@ -37,10 +37,6 @@ type RedisConfig struct { // DB is the database connection for fallback and replay operations DB db.Database - // Logger is the logging implementation to use. - // Optional, but recommended for production use. - Logger logging.Logger - // Counter is the counter implementation to use. Counter counter.Counter @@ -52,7 +48,6 @@ type RedisConfig struct { // This provides truly atomic operations via Redis INCRBY commands type counterService struct { db db.Database - logger logging.Logger counter counter.Counter // Fallback to direct DB implementation when Redis fails @@ -75,9 +70,6 @@ type CounterConfig struct { // DB is the database connection for fallback and replay operations DB db.Database - // Logger is the logging implementation to use - Logger logging.Logger - // Counter is the distributed counter implementation to use Counter counter.Counter @@ -123,8 +115,7 @@ func NewCounter(config CounterConfig) (Service, error) { // Create the direct DB fallback service dbFallback, err := New(Config{ - DB: config.DB, - Logger: config.Logger, + DB: config.DB, }) if err != nil { return nil, fmt.Errorf("failed to create DB fallback: %w", err) @@ -132,7 +123,6 @@ func NewCounter(config CounterConfig) (Service, error) { s := &counterService{ db: config.DB, - logger: config.Logger, counter: config.Counter, dbFallback: dbFallback, ttl: ttl, @@ -143,7 +133,6 @@ func NewCounter(config CounterConfig) (Service, error) { }), dbCircuitBreaker: circuitbreaker.New[any]( "usagelimiter_db_writes", - circuitbreaker.WithLogger(config.Logger), ), } @@ -270,7 +259,7 @@ func (s *counterService) initializeFromDatabase(ctx context.Context, req UsageRe wasSet, err := s.counter.SetIfNotExists(ctx, redisKey, initValue, s.ttl) if err != nil { - s.logger.Debug("failed to initialize counter with SetIfNotExists, falling back to DB", "error", err, "keyID", req.KeyID) + logger.Debug("failed to initialize counter with SetIfNotExists, falling back to DB", "error", err, "keyID", req.KeyID) return s.dbFallback.Limit(ctx, req) } @@ -288,7 +277,7 @@ func (s *counterService) initializeFromDatabase(ctx context.Context, req UsageRe // Another node already initialized the key, check if we have enough after decrement remaining, exists, success, err := s.counter.DecrementIfExists(ctx, redisKey, int64(req.Cost)) if err != nil || !exists { - s.logger.Debug("failed to decrement after initialization attempt", "error", err, "exists", exists, "keyID", req.KeyID) + logger.Debug("failed to decrement after initialization attempt", "error", err, "exists", exists, "keyID", req.KeyID) return s.dbFallback.Limit(ctx, req) } @@ -301,7 +290,7 @@ func (s *counterService) replayRequests() { for change := range s.replayBuffer.Consume() { err := s.syncWithDB(context.Background(), change) if err != nil { - s.logger.Error("failed to replay credit change", "error", err) + logger.Error("failed to replay credit change", "error", err) } } } @@ -335,7 +324,7 @@ func (s *counterService) syncWithDB(ctx context.Context, change CreditChange) er func (s *counterService) Close() error { ctx := context.Background() - s.logger.Debug("beginning graceful shutdown of usage limiter") + logger.Debug("beginning graceful shutdown of usage limiter") // Set a reasonable timeout for draining if context doesn't have one if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > 30*time.Second { @@ -353,22 +342,22 @@ func (s *counterService) Close() error { stopRepeater := repeat.Every(100*time.Millisecond, func() { remaining := s.replayBuffer.Size() if remaining == 0 { - s.logger.Debug("usage limiter replay buffer drained successfully") + logger.Debug("usage limiter replay buffer drained successfully") close(done) return } - s.logger.Debug("waiting for replay buffer to drain", "remaining", remaining) + logger.Debug("waiting for replay buffer to drain", "remaining", remaining) }) defer stopRepeater() select { case <-ctx.Done(): - s.logger.Warn("shutdown timeout reached, actively draining remaining buffer items") + logger.Warn("shutdown timeout reached, actively draining remaining buffer items") // Actively drain any remaining items to avoid data loss for { remaining := s.replayBuffer.Size() if remaining == 0 { - s.logger.Debug("successfully drained all remaining buffer items") + logger.Debug("successfully drained all remaining buffer items") break } @@ -377,7 +366,7 @@ func (s *counterService) Close() error { case change := <-s.replayBuffer.Consume(): err := s.syncWithDB(context.Background(), change) if err != nil { - s.logger.Error("failed to sync credit change during shutdown", "error", err) + logger.Error("failed to sync credit change during shutdown", "error", err) } default: // Channel is closed and empty @@ -386,7 +375,7 @@ func (s *counterService) Close() error { return nil case <-done: - s.logger.Debug("usage limiter replay buffer drained successfully") + logger.Debug("usage limiter replay buffer drained successfully") return nil } } diff --git a/internal/services/usagelimiter/service.go b/internal/services/usagelimiter/service.go index 25ee5d72e8..14e6eb5cc0 100644 --- a/internal/services/usagelimiter/service.go +++ b/internal/services/usagelimiter/service.go @@ -5,21 +5,18 @@ import ( "github.com/unkeyed/unkey/pkg/assert" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // service implements the direct DB-based usage limiter type service struct { - db db.Database - logger logging.Logger + db db.Database } var _ Service = (*service)(nil) // Config for the direct DB implementation type Config struct { - DB db.Database - Logger logging.Logger + DB db.Database } // New creates a new direct DB-based usage limiter service. @@ -28,14 +25,12 @@ type Config struct { func New(config Config) (*service, error) { if err := assert.All( assert.NotNil(config.DB, "db is required"), - assert.NotNil(config.Logger, "logger is required"), ); err != nil { return nil, fmt.Errorf("invalid usagelimiter service config: %w", err) } return &service{ - db: config.DB, - logger: config.Logger, + db: config.DB, }, nil } @@ -61,7 +56,6 @@ func NewRedisWithCounter(config RedisConfig) (Service, error) { //nolint:exhaustruct // ReplayWorkers defaults to 8 in NewCounter when unset return NewCounter(CounterConfig{ DB: config.DB, - Logger: config.Logger, Counter: config.Counter, TTL: config.TTL, }) diff --git a/pkg/cache/BUILD.bazel b/pkg/cache/BUILD.bazel index 361fbac52f..4e9cecaac8 100644 --- a/pkg/cache/BUILD.bazel +++ b/pkg/cache/BUILD.bazel @@ -18,7 +18,7 @@ go_library( "//pkg/clock", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/prometheus/metrics", "//pkg/repeat", "//pkg/timing", @@ -39,7 +39,6 @@ go_test( ":cache", "//pkg/clock", "//pkg/db", - "//pkg/otel/logging", "//pkg/sim", "@com_github_stretchr_testify//require", ], diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index c3f53137b2..a8b692ad57 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -13,7 +13,7 @@ import ( "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/prometheus/metrics" "github.com/unkeyed/unkey/pkg/repeat" "github.com/unkeyed/unkey/pkg/timing" @@ -23,7 +23,6 @@ type cache[K comparable, V any] struct { otter otter.Cache[K, swrEntry[V]] fresh time.Duration stale time.Duration - logger logging.Logger resource string clock clock.Clock @@ -42,8 +41,6 @@ type Config[K comparable, V any] struct { // fetching from the origin server Stale time.Duration - Logger logging.Logger - // Start evicting the least recently used entry when the cache grows to MaxSize MaxSize int @@ -58,7 +55,6 @@ var _ Cache[any, any] = (*cache[any, any])(nil) func New[K comparable, V any](config Config[K, V]) (Cache[K, V], error) { if err := assert.All( assert.NotNil(config.Clock, "clock is required"), - assert.NotNil(config.Logger, "logger is required"), ); err != nil { return nil, fmt.Errorf("invalid cache config: %w", err) } @@ -85,7 +81,6 @@ func New[K comparable, V any](config Config[K, V]) (Cache[K, V], error) { otter: otter, fresh: config.Fresh, stale: config.Stale, - logger: config.Logger, resource: config.Resource, clock: config.Clock, revalidateC: make(chan func(), 1000), @@ -304,7 +299,7 @@ func (c *cache[K, V]) revalidate( v, err := refreshFromOrigin(ctx) if err != nil && !db.IsNotFound(err) { - c.logger.Warn("failed to revalidate", "error", err.Error(), "key", key) + logger.Warn("failed to revalidate", "error", err.Error(), "key", key) } switch op(err) { @@ -560,7 +555,7 @@ func (c *cache[K, V]) revalidateWithCanonicalKey( v, canonicalKey, err := refreshFromOrigin(ctx) if err != nil && !db.IsNotFound(err) { - c.logger.Warn("failed to revalidate with canonical key", "error", err.Error()) + logger.Warn("failed to revalidate with canonical key", "error", err.Error()) return } @@ -607,7 +602,7 @@ func (c *cache[K, V]) revalidateMany( values, err := refreshFromOrigin(ctx, keysToRefresh) if err != nil && !db.IsNotFound(err) { - c.logger.Warn("failed to revalidate many", "error", err.Error(), "keys", keysToRefresh) + logger.Warn("failed to revalidate many", "error", err.Error(), "keys", keysToRefresh) } switch op(err) { diff --git a/pkg/cache/cache_test.go b/pkg/cache/cache_test.go index 87b39f44b2..911f823225 100644 --- a/pkg/cache/cache_test.go +++ b/pkg/cache/cache_test.go @@ -10,7 +10,6 @@ import ( "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/clock" - "github.com/unkeyed/unkey/pkg/otel/logging" ) func TestWriteRead(t *testing.T) { @@ -20,7 +19,6 @@ func TestWriteRead(t *testing.T) { Fresh: time.Minute, Stale: time.Minute * 5, - Logger: logging.NewNoop(), Resource: "test", Clock: clock.New(), }) require.NoError(t, err) @@ -38,7 +36,6 @@ func TestEviction(t *testing.T) { Fresh: time.Second, Stale: time.Second, - Logger: logging.NewNoop(), Resource: "test", Clock: clk, }) @@ -61,7 +58,6 @@ func TestRefresh(t *testing.T) { Fresh: time.Second * 2, Stale: time.Minute * 5, - Logger: logging.NewNoop(), Resource: "test", Clock: clk, }) @@ -84,7 +80,6 @@ func TestNull(t *testing.T) { MaxSize: 10_000, Fresh: time.Second * 1, Stale: time.Minute * 5, - Logger: logging.NewNoop(), Resource: "test", Clock: clock.New(), }) diff --git a/pkg/cache/clustering/BUILD.bazel b/pkg/cache/clustering/BUILD.bazel index 335b560629..424bdbde9a 100644 --- a/pkg/cache/clustering/BUILD.bazel +++ b/pkg/cache/clustering/BUILD.bazel @@ -15,7 +15,7 @@ go_library( "//pkg/batch", "//pkg/cache", "//pkg/eventstream", - "//pkg/otel/logging", + "//pkg/logger", ], ) @@ -33,7 +33,6 @@ go_test( "//pkg/cache", "//pkg/clock", "//pkg/eventstream", - "//pkg/otel/logging", "//pkg/testutil/containers", "//pkg/uid", "@com_github_stretchr_testify//require", diff --git a/pkg/cache/clustering/cluster_cache.go b/pkg/cache/clustering/cluster_cache.go index df57bd8ae7..d6705a131a 100644 --- a/pkg/cache/clustering/cluster_cache.go +++ b/pkg/cache/clustering/cluster_cache.go @@ -10,7 +10,7 @@ import ( "github.com/unkeyed/unkey/pkg/batch" "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/eventstream" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) // ClusterCache wraps a local cache and automatically handles distributed invalidation @@ -21,7 +21,6 @@ type ClusterCache[K comparable, V any] struct { producer eventstream.Producer[*cachev1.CacheInvalidationEvent] cacheName string nodeID string - logger logging.Logger keyToString func(K) string stringToKey func(string) (K, error) onInvalidation func(ctx context.Context, key K) @@ -42,9 +41,6 @@ type Config[K comparable, V any] struct { // Required for receiving invalidations from other nodes Dispatcher *InvalidationDispatcher - // Logger for debugging and error reporting - Logger logging.Logger - // Optional node ID (defaults to hostname) NodeID string @@ -101,7 +97,6 @@ func New[K comparable, V any](config Config[K, V]) (*ClusterCache[K, V], error) topic: config.Topic, cacheName: config.LocalCache.Name(), nodeID: config.NodeID, - logger: config.Logger, keyToString: keyToString, stringToKey: stringToKey, onInvalidation: func(ctx context.Context, key K) { @@ -124,7 +119,7 @@ func New[K comparable, V any](config Config[K, V]) (*ClusterCache[K, V], error) Flush: func(ctx context.Context, events []*cachev1.CacheInvalidationEvent) { err := c.producer.Produce(ctx, events...) if err != nil { - c.logger.Error("Failed to broadcast cache invalidations", + logger.Error("Failed to broadcast cache invalidations", "error", err, "cache", c.cacheName, "event_count", len(events)) @@ -257,7 +252,7 @@ func (c *ClusterCache[K, V]) HandleInvalidation(ctx context.Context, event *cach // Convert string key back to K type key, err := c.stringToKey(event.GetCacheKey()) if err != nil { - c.logger.Warn( + logger.Warn( "Failed to convert cache key", "cache", c.cacheName, "key", event.GetCacheKey(), diff --git a/pkg/cache/clustering/consume_events_test.go b/pkg/cache/clustering/consume_events_test.go index 53c11275a7..fa94b48c97 100644 --- a/pkg/cache/clustering/consume_events_test.go +++ b/pkg/cache/clustering/consume_events_test.go @@ -12,7 +12,6 @@ import ( "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/eventstream" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/pkg/uid" ) @@ -29,7 +28,6 @@ func TestClusterCache_ConsumesInvalidationAndRemovesFromCache(t *testing.T) { Brokers: brokers, Topic: topicName, InstanceID: uid.New(uid.TestPrefix), - Logger: logging.NewNoop(), }) require.NoError(t, err) @@ -50,7 +48,6 @@ func TestClusterCache_ConsumesInvalidationAndRemovesFromCache(t *testing.T) { Stale: 10 * time.Minute, MaxSize: 1000, Resource: "test-cache", - Logger: logging.NewNoop(), Clock: clock.New(), }) require.NoError(t, err) diff --git a/pkg/cache/clustering/dispatcher.go b/pkg/cache/clustering/dispatcher.go index 214b59e111..3c87be6ade 100644 --- a/pkg/cache/clustering/dispatcher.go +++ b/pkg/cache/clustering/dispatcher.go @@ -7,7 +7,6 @@ import ( cachev1 "github.com/unkeyed/unkey/gen/proto/cache/v1" "github.com/unkeyed/unkey/pkg/assert" "github.com/unkeyed/unkey/pkg/eventstream" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // InvalidationHandler is an interface that cluster caches implement @@ -27,17 +26,15 @@ type InvalidationDispatcher struct { mu sync.RWMutex handlers map[string]InvalidationHandler // keyed by cache name consumer eventstream.Consumer[*cachev1.CacheInvalidationEvent] - logger logging.Logger } // NewInvalidationDispatcher creates a new dispatcher that routes invalidation // events to registered caches. // -// Returns an error if topic or logger is nil - use NewNoopDispatcher() if clustering is disabled. -func NewInvalidationDispatcher(topic *eventstream.Topic[*cachev1.CacheInvalidationEvent], logger logging.Logger) (*InvalidationDispatcher, error) { +// Returns an error if topic is nil - use NewNoopDispatcher() if clustering is disabled. +func NewInvalidationDispatcher(topic *eventstream.Topic[*cachev1.CacheInvalidationEvent]) (*InvalidationDispatcher, error) { err := assert.All( assert.NotNil(topic, "topic is required for InvalidationDispatcher - use NewNoopDispatcher() if clustering is disabled"), - assert.NotNil(logger, "logger is required for InvalidationDispatcher"), ) if err != nil { return nil, err @@ -47,7 +44,6 @@ func NewInvalidationDispatcher(topic *eventstream.Topic[*cachev1.CacheInvalidati mu: sync.RWMutex{}, consumer: nil, handlers: make(map[string]InvalidationHandler), - logger: logger, } d.consumer = topic.NewConsumer() diff --git a/pkg/cache/clustering/e2e_test.go b/pkg/cache/clustering/e2e_test.go index 9af8dc6265..9f9b1a21c0 100644 --- a/pkg/cache/clustering/e2e_test.go +++ b/pkg/cache/clustering/e2e_test.go @@ -12,7 +12,6 @@ import ( "github.com/unkeyed/unkey/pkg/cache/clustering" "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/eventstream" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/pkg/uid" ) @@ -25,12 +24,10 @@ func TestClusterCache_EndToEndDistributedInvalidation(t *testing.T) { topicName := fmt.Sprintf("test-clustering-e2e-%s", uid.New(uid.TestPrefix)) // Create eventstream topic with real logger for debugging - logger := logging.New() topic, err := eventstream.NewTopic[*cachev1.CacheInvalidationEvent](eventstream.TopicConfig{ Brokers: brokers, Topic: topicName, InstanceID: uid.New(uid.TestPrefix), - Logger: logger, }) require.NoError(t, err) @@ -45,7 +42,7 @@ func TestClusterCache_EndToEndDistributedInvalidation(t *testing.T) { require.NoError(t, err) // Create dispatcher (one per process in production) - dispatcher, err := clustering.NewInvalidationDispatcher(topic, logger) + dispatcher, err := clustering.NewInvalidationDispatcher(topic) require.NoError(t, err) defer func() { require.NoError(t, dispatcher.Close()) }() @@ -60,7 +57,6 @@ func TestClusterCache_EndToEndDistributedInvalidation(t *testing.T) { Stale: 10 * time.Minute, MaxSize: 1000, Resource: "test-cache", - Logger: logging.NewNoop(), Clock: clock.New(), }) if err != nil { @@ -73,7 +69,6 @@ func TestClusterCache_EndToEndDistributedInvalidation(t *testing.T) { Topic: topic, Dispatcher: dispatcher, NodeID: nodeID, - Logger: logger, }) if err != nil { return nil, nil, err diff --git a/pkg/cache/clustering/noop.go b/pkg/cache/clustering/noop.go index 833b6b039c..ad6a0b4a6e 100644 --- a/pkg/cache/clustering/noop.go +++ b/pkg/cache/clustering/noop.go @@ -1,10 +1,6 @@ // nolint: all package clustering -import ( - "github.com/unkeyed/unkey/pkg/otel/logging" -) - // noopDispatcher is a no-op implementation that does nothing. // Used when clustering is disabled. type noopDispatcher struct{} @@ -17,6 +13,5 @@ func (n *noopDispatcher) Close() error { return nil } func NewNoopDispatcher() *InvalidationDispatcher { return &InvalidationDispatcher{ handlers: make(map[string]InvalidationHandler), - logger: logging.NewNoop(), } } diff --git a/pkg/cache/clustering/produce_events_test.go b/pkg/cache/clustering/produce_events_test.go index 3802bca64f..3bb803c8cb 100644 --- a/pkg/cache/clustering/produce_events_test.go +++ b/pkg/cache/clustering/produce_events_test.go @@ -14,7 +14,6 @@ import ( "github.com/unkeyed/unkey/pkg/cache/clustering" "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/eventstream" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/pkg/uid" ) @@ -31,7 +30,6 @@ func TestClusterCache_ProducesInvalidationOnRemoveAndSetNull(t *testing.T) { Brokers: brokers, Topic: topicName, InstanceID: uid.New(uid.TestPrefix), - Logger: logging.NewNoop(), }) require.NoError(t, err) @@ -56,7 +54,6 @@ func TestClusterCache_ProducesInvalidationOnRemoveAndSetNull(t *testing.T) { Stale: 10 * time.Minute, MaxSize: 1000, Resource: "test-cache", - Logger: logging.NewNoop(), Clock: clock.New(), }) require.NoError(t, err) @@ -67,7 +64,6 @@ func TestClusterCache_ProducesInvalidationOnRemoveAndSetNull(t *testing.T) { Topic: topic, Dispatcher: dispatcher, NodeID: "test-node-1", - Logger: logging.NewNoop(), }) require.NoError(t, err) diff --git a/pkg/cache/doc.go b/pkg/cache/doc.go index 9b1bd91904..2ef1c8de85 100644 --- a/pkg/cache/doc.go +++ b/pkg/cache/doc.go @@ -13,7 +13,6 @@ // Fresh: time.Minute, // Items considered fresh for 1 minute // Stale: time.Hour, // Items can be served stale for up to 1 hour // MaxSize: 10000, // Store up to 10,000 items -// Logger: logger, // Resource: "users", // For metrics and logging // }) // diff --git a/pkg/cache/many_test.go b/pkg/cache/many_test.go index 2939f7920e..d20a508746 100644 --- a/pkg/cache/many_test.go +++ b/pkg/cache/many_test.go @@ -11,7 +11,6 @@ import ( "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) func TestGetMany(t *testing.T) { @@ -20,7 +19,6 @@ func TestGetMany(t *testing.T) { MaxSize: 10_000, Fresh: time.Minute, Stale: time.Minute * 5, - Logger: logging.NewNoop(), Resource: "test", Clock: clock.New(), }) @@ -108,7 +106,6 @@ func TestGetMany_Eviction(t *testing.T) { MaxSize: 10_000, Fresh: time.Second, Stale: time.Second, - Logger: logging.NewNoop(), Resource: "test", Clock: clk, }) @@ -136,7 +133,6 @@ func TestSetMany(t *testing.T) { MaxSize: 10_000, Fresh: time.Minute, Stale: time.Minute * 5, - Logger: logging.NewNoop(), Resource: "test", Clock: clock.New(), }) @@ -188,7 +184,6 @@ func TestSetNullMany(t *testing.T) { MaxSize: 10_000, Fresh: time.Minute, Stale: time.Minute * 5, - Logger: logging.NewNoop(), Resource: "test", Clock: clock.New(), }) @@ -229,7 +224,6 @@ func TestSWRMany(t *testing.T) { c, err := cache.New(cache.Config[string, string]{ Fresh: 1 * time.Minute, Stale: 5 * time.Minute, - Logger: logging.NewNoop(), MaxSize: 100, Resource: "test", Clock: mockClock, diff --git a/pkg/cache/simulation_test.go b/pkg/cache/simulation_test.go index 02ca027f2d..e1e2bcb5e4 100644 --- a/pkg/cache/simulation_test.go +++ b/pkg/cache/simulation_test.go @@ -10,7 +10,6 @@ import ( "github.com/stretchr/testify/require" "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/clock" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/sim" ) @@ -108,7 +107,6 @@ func TestSimulation(t *testing.T) { Clock: clk, Fresh: fresh, Stale: stale, - Logger: logging.NewNoop(), MaxSize: rng.IntN(1_000_000) + 1, // Ensure at least size 1 Resource: "test", }) diff --git a/pkg/cache/swr_test.go b/pkg/cache/swr_test.go index e248bb79ef..9538576371 100644 --- a/pkg/cache/swr_test.go +++ b/pkg/cache/swr_test.go @@ -11,18 +11,15 @@ import ( "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) func TestSWR_CacheHit(t *testing.T) { ctx := context.Background() mockClock := clock.NewTestClock() - logger := logging.New() c, err := cache.New(cache.Config[string, string]{ Fresh: 1 * time.Minute, Stale: 5 * time.Minute, - Logger: logger, MaxSize: 100, Resource: "test", Clock: mockClock, diff --git a/pkg/circuitbreaker/BUILD.bazel b/pkg/circuitbreaker/BUILD.bazel index 9f24c7ce34..e353995c39 100644 --- a/pkg/circuitbreaker/BUILD.bazel +++ b/pkg/circuitbreaker/BUILD.bazel @@ -12,7 +12,7 @@ go_library( visibility = ["//visibility:public"], deps = [ "//pkg/clock", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/prometheus/metrics", ], ) @@ -24,7 +24,6 @@ go_test( embed = [":circuitbreaker"], deps = [ "//pkg/clock", - "//pkg/otel/logging", "@com_github_stretchr_testify//require", ], ) diff --git a/pkg/circuitbreaker/lib.go b/pkg/circuitbreaker/lib.go index 21aba1e492..c6eed00f22 100644 --- a/pkg/circuitbreaker/lib.go +++ b/pkg/circuitbreaker/lib.go @@ -6,7 +6,7 @@ import ( "time" "github.com/unkeyed/unkey/pkg/clock" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/prometheus/metrics" ) @@ -20,8 +20,6 @@ type CB[Res any] struct { // need to modify the clock for testing config *config - logger logging.Logger - // State of the circuit state State @@ -63,8 +61,6 @@ type config struct { // Clock to use for timing, defaults to the system clock but can be overridden for testing clock clock.Clock - - logger logging.Logger } // WithMaxRequests sets the maximum number of requests allowed through during @@ -118,13 +114,6 @@ func WithClock(clock clock.Clock) applyConfig { } } -// WithLogger sets the logger for circuit breaker debug output. -func WithLogger(logger logging.Logger) applyConfig { - return func(c *config) { - c.logger = logger - } -} - // applyConfig is a functional option for configuring a circuit breaker. // Use the With* functions to create options. type applyConfig func(*config) @@ -143,7 +132,6 @@ func New[Res any](name string, applyConfigs ...applyConfig) *CB[Res] { }, tripThreshold: 5, clock: clock.New(), - logger: logging.NewNoop(), } for _, apply := range applyConfigs { @@ -153,7 +141,6 @@ func New[Res any](name string, applyConfigs ...applyConfig) *CB[Res] { cb := &CB[Res]{ Mutex: sync.Mutex{}, config: cfg, - logger: cfg.logger, state: Closed, resetCountersAt: cfg.clock.Now().Add(cfg.cyclicPeriod), resetStateAt: cfg.clock.Now().Add(cfg.timeout), @@ -170,7 +157,6 @@ func New[Res any](name string, applyConfigs ...applyConfig) *CB[Res] { var _ CircuitBreaker[any] = &CB[any]{ Mutex: sync.Mutex{}, config: nil, - logger: nil, state: Closed, resetCountersAt: time.Time{}, resetStateAt: time.Time{}, @@ -225,7 +211,7 @@ func (cb *CB[Res]) preflight(_ context.Context) error { return ErrTripped } - cb.logger.Debug("circuit breaker state", "state", string(cb.state), "requests", cb.requests, "maxRequests", cb.config.maxRequests) + logger.Debug("circuit breaker state", "state", string(cb.state), "requests", cb.requests, "maxRequests", cb.config.maxRequests) if cb.state == HalfOpen && cb.requests >= cb.config.maxRequests { return ErrTooManyRequests } diff --git a/pkg/circuitbreaker/lib_test.go b/pkg/circuitbreaker/lib_test.go index 94c1e9047a..5e6997e4c3 100644 --- a/pkg/circuitbreaker/lib_test.go +++ b/pkg/circuitbreaker/lib_test.go @@ -8,7 +8,6 @@ import ( "github.com/stretchr/testify/require" "github.com/unkeyed/unkey/pkg/clock" - "github.com/unkeyed/unkey/pkg/otel/logging" ) var errTestDownstream = errors.New("downstream test error") @@ -16,7 +15,7 @@ var errTestDownstream = errors.New("downstream test error") func TestCircuitBreakerStates(t *testing.T) { c := clock.NewTestClock() - cb := New[int]("test", WithCyclicPeriod(5*time.Second), WithClock(c), WithTripThreshold(3), WithLogger(logging.NewNoop())) + cb := New[int]("test", WithCyclicPeriod(5*time.Second), WithClock(c), WithTripThreshold(3)) // Test Closed State for i := 0; i < 3; i++ { diff --git a/pkg/clickhouse/BUILD.bazel b/pkg/clickhouse/BUILD.bazel index acaf3e3dad..0430108157 100644 --- a/pkg/clickhouse/BUILD.bazel +++ b/pkg/clickhouse/BUILD.bazel @@ -23,7 +23,7 @@ go_library( "//pkg/clickhouse/schema", "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/retry", "@com_github_clickhouse_clickhouse_go_v2//:clickhouse-go", "@com_github_clickhouse_clickhouse_go_v2//lib/driver", @@ -43,7 +43,6 @@ go_test( deps = [ "//pkg/array", "//pkg/clickhouse/schema", - "//pkg/otel/logging", "//pkg/testutil/containers", "//pkg/uid", "@com_github_clickhouse_clickhouse_go_v2//:clickhouse-go", diff --git a/pkg/clickhouse/billable_usage_test.go b/pkg/clickhouse/billable_usage_test.go index 3f9a2cf7cd..a08144d7c6 100644 --- a/pkg/clickhouse/billable_usage_test.go +++ b/pkg/clickhouse/billable_usage_test.go @@ -11,7 +11,6 @@ import ( "github.com/stretchr/testify/require" "github.com/unkeyed/unkey/pkg/clickhouse" "github.com/unkeyed/unkey/pkg/clickhouse/schema" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/pkg/uid" ) @@ -21,8 +20,7 @@ func TestGetBillableUsageAboveThreshold(t *testing.T) { // Create ClickHouse client using the clickhouse package client, err := clickhouse.New(clickhouse.Config{ - URL: dsn, - Logger: logging.NewNoop(), + URL: dsn, }) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, client.Close()) }) diff --git a/pkg/clickhouse/client.go b/pkg/clickhouse/client.go index 54fe22dd37..cdf44887e0 100644 --- a/pkg/clickhouse/client.go +++ b/pkg/clickhouse/client.go @@ -11,7 +11,7 @@ import ( "github.com/unkeyed/unkey/pkg/circuitbreaker" "github.com/unkeyed/unkey/pkg/clickhouse/schema" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/retry" ) @@ -20,7 +20,6 @@ import ( // high volumes of data while minimizing connection overhead. type clickhouse struct { conn ch.Conn - logger logging.Logger circuitBreaker *circuitbreaker.CB[struct{}] retry *retry.Retry @@ -44,9 +43,6 @@ type Config struct { // URL is the ClickHouse connection string // Format: clickhouse://username:password@host:port/database?param1=value1&... URL string - - // Logger for ClickHouse operations - Logger logging.Logger } // New creates a new ClickHouse client with the provided configuration. @@ -60,7 +56,6 @@ type Config struct { // // ch, err := clickhouse.New(clickhouse.Config{ // URL: "clickhouse://user:pass@clickhouse.example.com:9000/db", -// Logger: logger, // }) // if err != nil { // return fmt.Errorf("failed to initialize clickhouse: %w", err) @@ -71,17 +66,17 @@ func New(config Config) (*clickhouse, error) { return nil, fault.Wrap(err, fault.Internal("parsing clickhouse DSN failed")) } - config.Logger.Info("initializing clickhouse client") + logger.Info("initializing clickhouse client") opts.Debug = true opts.Debugf = func(format string, v ...any) { - config.Logger.Debug(fmt.Sprintf(format, v...)) + logger.Debug(fmt.Sprintf(format, v...)) } opts.MaxOpenConns = 50 opts.ConnMaxLifetime = time.Hour opts.ConnOpenStrategy = ch.ConnOpenRoundRobin opts.DialTimeout = 5 * time.Second // Fail fast on connection issues - config.Logger.Info("connecting to clickhouse") + logger.Info("connecting to clickhouse") conn, err := ch.Open(opts) if err != nil { return nil, fault.Wrap(err, fault.Internal("opening clickhouse failed")) @@ -105,8 +100,7 @@ func New(config Config) (*clickhouse, error) { } c := &clickhouse{ - conn: conn, - logger: config.Logger, + conn: conn, circuitBreaker: circuitbreaker.New[struct{}]( "clickhouse_insert", circuitbreaker.WithTripThreshold(5), @@ -141,7 +135,7 @@ func New(config Config) (*clickhouse, error) { Flush: func(ctx context.Context, rows []schema.ApiRequest) { table := "default.api_requests_raw_v2" if err := flush(c, ctx, table, rows); err != nil { - c.logger.Error("failed to flush batch", "table", table, "error", err.Error()) + logger.Error("failed to flush batch", "table", table, "error", err.Error()) } }, }) @@ -156,7 +150,7 @@ func New(config Config) (*clickhouse, error) { Flush: func(ctx context.Context, rows []schema.KeyVerification) { table := "default.key_verifications_raw_v2" if err := flush(c, ctx, table, rows); err != nil { - c.logger.Error("failed to flush batch", "table", table, "error", err.Error()) + logger.Error("failed to flush batch", "table", table, "error", err.Error()) } }, }) @@ -171,7 +165,7 @@ func New(config Config) (*clickhouse, error) { Flush: func(ctx context.Context, rows []schema.Ratelimit) { table := "default.ratelimits_raw_v2" if err := flush(c, ctx, table, rows); err != nil { - c.logger.Error("failed to flush batch", "table", table, "error", err.Error()) + logger.Error("failed to flush batch", "table", table, "error", err.Error()) } }, }) @@ -186,7 +180,7 @@ func New(config Config) (*clickhouse, error) { Flush: func(ctx context.Context, rows []schema.BuildStepV1) { table := "default.build_steps_v1" if err := flush(c, ctx, table, rows); err != nil { - c.logger.Error("failed to flush batch", "table", table, "error", err.Error()) + logger.Error("failed to flush batch", "table", table, "error", err.Error()) } }, }) @@ -201,7 +195,7 @@ func New(config Config) (*clickhouse, error) { Flush: func(ctx context.Context, rows []schema.BuildStepLogV1) { table := "default.build_step_logs_v1" if err := flush(c, ctx, table, rows); err != nil { - c.logger.Error("failed to flush batch", "table", table, "error", err.Error()) + logger.Error("failed to flush batch", "table", table, "error", err.Error()) } }, }) @@ -216,7 +210,7 @@ func New(config Config) (*clickhouse, error) { Flush: func(ctx context.Context, rows []schema.SentinelRequest) { table := "default.sentinel_requests_raw_v1" if err := flush(c, ctx, table, rows); err != nil { - c.logger.Error("failed to flush batch", "table", table, "error", err.Error()) + logger.Error("failed to flush batch", "table", table, "error", err.Error()) } }, }) diff --git a/pkg/clickhouse/doc.go b/pkg/clickhouse/doc.go index aa15fb9a93..940d0d36fd 100644 --- a/pkg/clickhouse/doc.go +++ b/pkg/clickhouse/doc.go @@ -18,7 +18,6 @@ // // Create a ClickHouse client // ch, err := clickhouse.New(clickhouse.Config{ // URL: "clickhouse://user:pass@clickhouse.example.com:9000/db?secure=true", -// Logger: logger, // }) // if err != nil { // return fmt.Errorf("failed to create clickhouse client: %w", err) diff --git a/pkg/clickhouse/flush.go b/pkg/clickhouse/flush.go index f5b22ec16c..9d1c70e05e 100644 --- a/pkg/clickhouse/flush.go +++ b/pkg/clickhouse/flush.go @@ -7,6 +7,7 @@ import ( ch "github.com/ClickHouse/clickhouse-go/v2" "github.com/ClickHouse/clickhouse-go/v2/lib/driver" "github.com/unkeyed/unkey/pkg/fault" + "github.com/unkeyed/unkey/pkg/logger" ) // flush writes a batch of rows to the specified ClickHouse table. @@ -35,7 +36,7 @@ func flush[T any](c *clickhouse, ctx context.Context, table string, rows []T) er } defer func() { if err = batch.Close(); err != nil { - c.logger.Error("failed to close batch", "error", err.Error()) + logger.Error("failed to close batch", "error", err.Error()) } }() diff --git a/pkg/clickhouse/noop.go b/pkg/clickhouse/noop.go index e3f0e6d95d..c4cac2a521 100644 --- a/pkg/clickhouse/noop.go +++ b/pkg/clickhouse/noop.go @@ -102,7 +102,6 @@ func (n *noop) Close() error { // if config.ClickhouseURL != "" { // ch, err := clickhouse.New(clickhouse.Config{ // URL: config.ClickhouseURL, -// Logger: logger, // }) // if err != nil { // logger.Warn("Failed to initialize ClickHouse, analytics will be disabled") diff --git a/pkg/clickhouse/query-parser/BUILD.bazel b/pkg/clickhouse/query-parser/BUILD.bazel index 28b082324f..ac1c4ee5e4 100644 --- a/pkg/clickhouse/query-parser/BUILD.bazel +++ b/pkg/clickhouse/query-parser/BUILD.bazel @@ -18,7 +18,7 @@ go_library( deps = [ "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "@com_github_aftership_clickhouse_sql_parser//parser", ], ) @@ -39,7 +39,6 @@ go_test( deps = [ "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", "@com_github_stretchr_testify//require", ], ) diff --git a/pkg/clickhouse/query-parser/errors_test.go b/pkg/clickhouse/query-parser/errors_test.go index 768557e769..e0ce829069 100644 --- a/pkg/clickhouse/query-parser/errors_test.go +++ b/pkg/clickhouse/query-parser/errors_test.go @@ -7,7 +7,6 @@ import ( "github.com/stretchr/testify/require" "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" ) func TestParser_ErrorCodes(t *testing.T) { @@ -21,7 +20,6 @@ func TestParser_ErrorCodes(t *testing.T) { { name: "invalid SQL syntax", config: Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", AllowedTables: []string{ "default.keys_v2", @@ -34,7 +32,6 @@ func TestParser_ErrorCodes(t *testing.T) { { name: "invalid table", config: Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", AllowedTables: []string{ "default.keys_v2", @@ -47,7 +44,6 @@ func TestParser_ErrorCodes(t *testing.T) { { name: "invalid function", config: Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", AllowedTables: []string{ "default.keys_v2", @@ -60,7 +56,6 @@ func TestParser_ErrorCodes(t *testing.T) { { name: "query not supported", config: Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", AllowedTables: []string{ "default.keys_v2", diff --git a/pkg/clickhouse/query-parser/extract_test.go b/pkg/clickhouse/query-parser/extract_test.go index 2c354896dc..70145692bd 100644 --- a/pkg/clickhouse/query-parser/extract_test.go +++ b/pkg/clickhouse/query-parser/extract_test.go @@ -6,7 +6,6 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" ) func TestExtractColumnValues(t *testing.T) { @@ -99,7 +98,6 @@ func TestExtractColumnValues(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { parser := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_test", TableAliases: map[string]string{"key_verifications": "default.key_verifications_raw_v2"}, AllowedTables: []string{"default.key_verifications_raw_v2"}, diff --git a/pkg/clickhouse/query-parser/filter_test.go b/pkg/clickhouse/query-parser/filter_test.go index cd30b89b1e..74a120ff25 100644 --- a/pkg/clickhouse/query-parser/filter_test.go +++ b/pkg/clickhouse/query-parser/filter_test.go @@ -6,12 +6,10 @@ import ( "github.com/stretchr/testify/require" chquery "github.com/unkeyed/unkey/pkg/clickhouse/query-parser" - "github.com/unkeyed/unkey/pkg/otel/logging" ) func TestParser_WorkspaceFilter(t *testing.T) { p := chquery.NewParser(chquery.Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", AllowedTables: []string{ "default.keys_v2", @@ -26,7 +24,6 @@ func TestParser_WorkspaceFilter(t *testing.T) { func TestParser_WorkspaceFilterWithExistingWhere(t *testing.T) { p := chquery.NewParser(chquery.Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_456", AllowedTables: []string{ "default.keys_v2", @@ -42,7 +39,6 @@ func TestParser_WorkspaceFilterWithExistingWhere(t *testing.T) { func TestSecurityFilterInjection(t *testing.T) { t.Run("no filter when SecurityFilters is empty", func(t *testing.T) { parser := chquery.NewParser(chquery.Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_test", SecurityFilters: nil, // No restriction Limit: 100, @@ -63,7 +59,6 @@ func TestSecurityFilterInjection(t *testing.T) { t.Run("injects single key_space_id filter", func(t *testing.T) { parser := chquery.NewParser(chquery.Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_test", SecurityFilters: []chquery.SecurityFilter{ { @@ -89,7 +84,6 @@ func TestSecurityFilterInjection(t *testing.T) { t.Run("injects multiple key_space_id filter", func(t *testing.T) { parser := chquery.NewParser(chquery.Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_test", SecurityFilters: []chquery.SecurityFilter{ { @@ -115,7 +109,6 @@ func TestSecurityFilterInjection(t *testing.T) { t.Run("combines with existing WHERE clause", func(t *testing.T) { parser := chquery.NewParser(chquery.Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_test", SecurityFilters: []chquery.SecurityFilter{ { @@ -141,7 +134,6 @@ func TestSecurityFilterInjection(t *testing.T) { t.Run("restricts access even when user queries different key_space_id", func(t *testing.T) { parser := chquery.NewParser(chquery.Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_test", SecurityFilters: []chquery.SecurityFilter{ { @@ -172,7 +164,6 @@ func TestSecurityFilterInjection(t *testing.T) { t.Run("supports multiple security filters simultaneously", func(t *testing.T) { parser := chquery.NewParser(chquery.Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_test", SecurityFilters: []chquery.SecurityFilter{ { @@ -203,7 +194,6 @@ func TestSecurityFilterInjection(t *testing.T) { func TestParser_WorkspaceFilterInjection(t *testing.T) { p := chquery.NewParser(chquery.Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_victim", Limit: 1000, AllowedTables: []string{ @@ -249,7 +239,6 @@ func TestParser_WorkspaceFilterInjection(t *testing.T) { func TestParser_SQLInjectionWithFilters(t *testing.T) { p := chquery.NewParser(chquery.Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", Limit: 1000, AllowedTables: []string{ @@ -295,7 +284,6 @@ func TestParser_SQLInjectionWithFilters(t *testing.T) { func TestParser_SpecialCharactersInFilters(t *testing.T) { p := chquery.NewParser(chquery.Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", Limit: 1000, AllowedTables: []string{ diff --git a/pkg/clickhouse/query-parser/limits_test.go b/pkg/clickhouse/query-parser/limits_test.go index ecf8889b22..a71c4ec5de 100644 --- a/pkg/clickhouse/query-parser/limits_test.go +++ b/pkg/clickhouse/query-parser/limits_test.go @@ -5,12 +5,10 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" ) func TestParser_EnforceLimit(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", Limit: 100, AllowedTables: []string{ @@ -26,7 +24,6 @@ func TestParser_EnforceLimit(t *testing.T) { func TestParser_AddLimit(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", Limit: 50, AllowedTables: []string{ @@ -42,7 +39,6 @@ func TestParser_AddLimit(t *testing.T) { func TestParser_PreserveSmallerLimit(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", Limit: 100, AllowedTables: []string{ @@ -58,7 +54,6 @@ func TestParser_PreserveSmallerLimit(t *testing.T) { func TestParser_LimitBypassAttempts(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", Limit: 10, AllowedTables: []string{ diff --git a/pkg/clickhouse/query-parser/parser.go b/pkg/clickhouse/query-parser/parser.go index c5966ed281..ea477587dd 100644 --- a/pkg/clickhouse/query-parser/parser.go +++ b/pkg/clickhouse/query-parser/parser.go @@ -7,18 +7,13 @@ import ( clickhouse "github.com/AfterShip/clickhouse-sql-parser/parser" "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // NewParser creates a new parser func NewParser(config Config) *Parser { - if config.Logger == nil { - config.Logger = logging.NewNoop() - } return &Parser{ stmt: nil, config: config, - logger: config.Logger, cteNames: make(map[string]bool), } } diff --git a/pkg/clickhouse/query-parser/tables_test.go b/pkg/clickhouse/query-parser/tables_test.go index 22e06501eb..29308aaccb 100644 --- a/pkg/clickhouse/query-parser/tables_test.go +++ b/pkg/clickhouse/query-parser/tables_test.go @@ -5,12 +5,10 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" ) func TestParser_TableAliases(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", TableAliases: map[string]string{ "keys": "default.keys_v2", @@ -28,7 +26,6 @@ func TestParser_TableAliases(t *testing.T) { func TestParser_BlockSystemTables(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", }) @@ -69,7 +66,6 @@ func TestParser_BlockSystemTables(t *testing.T) { func TestParser_AllowedTables(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", AllowedTables: []string{ "default.keys_v2", @@ -88,7 +84,6 @@ func TestParser_AllowedTables(t *testing.T) { func TestParser_BlockInformationSchema(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", }) @@ -121,7 +116,6 @@ func TestParser_BlockInformationSchema(t *testing.T) { func TestParser_UNIONWithTables(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", Limit: 1000, AllowedTables: []string{ @@ -172,7 +166,6 @@ func TestParser_UNIONWithTables(t *testing.T) { func TestParser_JOINWithTables(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", AllowedTables: []string{ "default.key_verifications_raw_v2", @@ -232,7 +225,6 @@ func TestParser_JOINWithTables(t *testing.T) { func TestParser_SubqueryWithTables(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", Limit: 10, AllowedTables: []string{ @@ -292,7 +284,6 @@ func TestParser_SubqueryWithTables(t *testing.T) { func TestParser_CTEWithTables(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", AllowedTables: []string{ "default.key_verifications_raw_v2", @@ -357,7 +348,6 @@ func TestParser_CTEWithTables(t *testing.T) { func TestParser_ScalarSubqueryWithTables(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", AllowedTables: []string{ "default.key_verifications_raw_v2", @@ -402,7 +392,6 @@ func TestParser_ScalarSubqueryWithTables(t *testing.T) { func TestParser_TableFunctions(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", AllowedTables: []string{ "default.key_verifications_raw_v2", diff --git a/pkg/clickhouse/query-parser/time_range.go b/pkg/clickhouse/query-parser/time_range.go index ade219c0d4..abef666087 100644 --- a/pkg/clickhouse/query-parser/time_range.go +++ b/pkg/clickhouse/query-parser/time_range.go @@ -9,6 +9,7 @@ import ( clickhouse "github.com/AfterShip/clickhouse-sql-parser/parser" "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" + "github.com/unkeyed/unkey/pkg/logger" ) // validateTimeRange ensures the query doesn't access data older than MaxQueryRangeDays @@ -308,7 +309,7 @@ func (p *Parser) extractTimestampFromExpr(valueExpr clickhouse.Expr) (time.Time, default: // Unsupported time function - log and return current time as safe default // RLS policies at database level will enforce retention regardless - p.logger.Warn("unsupported time function in retention validation, using current time as safe default", + logger.Warn("unsupported time function in retention validation, using current time as safe default", "function", funcName, "workspace_id", p.config.WorkspaceID, ) @@ -324,7 +325,7 @@ func (p *Parser) extractTimestampFromExpr(valueExpr clickhouse.Expr) (time.Time, default: // Unsupported expression type - log and return current time as safe default // RLS policies at database level will enforce retention regardless - p.logger.Warn( + logger.Warn( "unsupported timestamp expression type in retention validation, using current time as safe default", "type", fmt.Sprintf("%T", valueExpr), "workspace_id", p.config.WorkspaceID, diff --git a/pkg/clickhouse/query-parser/time_range_test.go b/pkg/clickhouse/query-parser/time_range_test.go index 51c8510fb8..3f990100d6 100644 --- a/pkg/clickhouse/query-parser/time_range_test.go +++ b/pkg/clickhouse/query-parser/time_range_test.go @@ -7,7 +7,6 @@ import ( "time" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" ) func TestParser_ValidateTimeRange_WithRetention(t *testing.T) { @@ -205,7 +204,6 @@ func TestParser_ValidateTimeRange_WithRetention(t *testing.T) { "default.key_verifications_per_hour_v2", }, MaxQueryRangeDays: tt.retentionDays, - Logger: logging.NewNoop(), }) _, err := parser.Parse(context.Background(), tt.query) @@ -232,7 +230,6 @@ func TestParser_ValidateTimeRange_NoRetentionLimit(t *testing.T) { "default.key_verifications_per_hour_v2", }, MaxQueryRangeDays: 0, // No limit - Logger: logging.NewNoop(), }) tests := []struct { @@ -300,7 +297,6 @@ func TestParser_ValidateTimeRange_DifferentOperators(t *testing.T) { "default.key_verifications_per_hour_v2", }, MaxQueryRangeDays: 7, - Logger: logging.NewNoop(), }) for _, tt := range tests { @@ -368,7 +364,6 @@ func TestParser_ValidateTimeRange_IntervalUnits(t *testing.T) { "default.key_verifications_per_hour_v2", }, MaxQueryRangeDays: 7, - Logger: logging.NewNoop(), }) for _, tt := range tests { @@ -394,7 +389,6 @@ func TestParser_InjectDefaultTimeFilter(t *testing.T) { "default.key_verifications_per_hour_v2", }, MaxQueryRangeDays: 7, - Logger: logging.NewNoop(), }) tests := []struct { @@ -473,7 +467,6 @@ func TestParser_ValidateTimeRange_EdgeCases(t *testing.T) { "default.key_verifications_per_hour_v2", }, MaxQueryRangeDays: tt.retention, - Logger: logging.NewNoop(), }) _, err := parser.Parse(context.Background(), tt.query) @@ -520,7 +513,6 @@ func TestParser_ValidateTimeRange_NumericTimestamps(t *testing.T) { "default.key_verifications_per_hour_v2", }, MaxQueryRangeDays: 7, - Logger: logging.NewNoop(), }) for _, tt := range tests { @@ -596,7 +588,6 @@ func TestParser_ValidateTimeRange_ReversedComparisons(t *testing.T) { "default.key_verifications_per_hour_v2", }, MaxQueryRangeDays: 7, - Logger: logging.NewNoop(), }) for _, tt := range tests { @@ -622,7 +613,6 @@ func TestParser_ValidateTimeRange_UpperBoundOnly(t *testing.T) { "default.key_verifications_per_hour_v2", }, MaxQueryRangeDays: 7, - Logger: logging.NewNoop(), }) tests := []struct { diff --git a/pkg/clickhouse/query-parser/types.go b/pkg/clickhouse/query-parser/types.go index 4a0058da5d..6654bc112c 100644 --- a/pkg/clickhouse/query-parser/types.go +++ b/pkg/clickhouse/query-parser/types.go @@ -2,7 +2,6 @@ package queryparser import ( clickhouse "github.com/AfterShip/clickhouse-sql-parser/parser" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // SecurityFilter represents a row-level security constraint @@ -19,13 +18,11 @@ type Config struct { SecurityFilters []SecurityFilter // Row-level security filters (auto-injected) Limit int MaxQueryRangeDays int32 // Maximum historical data range user can query in days - Logger logging.Logger } // Parser rewrites ClickHouse queries type Parser struct { config Config - logger logging.Logger stmt *clickhouse.SelectQuery cteNames map[string]bool // Tracks CTE names defined in WITH clause } diff --git a/pkg/clickhouse/query-parser/validation_test.go b/pkg/clickhouse/query-parser/validation_test.go index ed917c0009..9c374416c3 100644 --- a/pkg/clickhouse/query-parser/validation_test.go +++ b/pkg/clickhouse/query-parser/validation_test.go @@ -5,12 +5,10 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" ) func TestParser_BlockNonWhitelistedFunctions(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", AllowedTables: []string{ "default.key_verifications_raw_v2", @@ -70,7 +68,6 @@ func TestParser_BlockNonWhitelistedFunctions(t *testing.T) { func TestParser_AllowSafeFunctions(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", AllowedTables: []string{ "default.keys_v2", @@ -88,7 +85,6 @@ func TestParser_AllowSafeFunctions(t *testing.T) { func TestParser_OnlySelectAllowed(t *testing.T) { p := NewParser(Config{ - Logger: logging.NewNoop(), WorkspaceID: "ws_123", AllowedTables: []string{ "default.key_verifications_raw_v2", diff --git a/pkg/clickhouse/user.go b/pkg/clickhouse/user.go index 4c3dc5af3d..3f44f512e1 100644 --- a/pkg/clickhouse/user.go +++ b/pkg/clickhouse/user.go @@ -6,6 +6,7 @@ import ( "regexp" driver "github.com/ClickHouse/clickhouse-go/v2" + "github.com/unkeyed/unkey/pkg/logger" ) var ( @@ -98,7 +99,7 @@ func getTimeRetentionFilter(tableName string, retentionDays int32) string { // ConfigureUser creates or updates a ClickHouse user with all necessary permissions, quotas, and settings. // This is idempotent - it can be run multiple times to update settings. func (c *clickhouse) ConfigureUser(ctx context.Context, config UserConfig) error { - logger := c.logger.With("workspace_id", config.WorkspaceID, "username", config.Username) + logger.Info("configuring clickhouse user", "workspace_id", config.WorkspaceID, "username", config.Username) // Validate all identifiers to prevent SQL injection if err := validateIdentifiers(config); err != nil { diff --git a/pkg/counter/BUILD.bazel b/pkg/counter/BUILD.bazel index 175c9cca8a..ebb617c09d 100644 --- a/pkg/counter/BUILD.bazel +++ b/pkg/counter/BUILD.bazel @@ -11,7 +11,7 @@ go_library( visibility = ["//visibility:public"], deps = [ "//pkg/assert", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/otel/tracing", "@com_github_redis_go_redis_v9//:go-redis", ], @@ -24,7 +24,6 @@ go_test( embed = [":counter"], deps = [ "//pkg/dockertest", - "//pkg/otel/logging", "//pkg/uid", "@com_github_stretchr_testify//require", ], diff --git a/pkg/counter/doc.go b/pkg/counter/doc.go index 84d91980d0..9c4a76afeb 100644 --- a/pkg/counter/doc.go +++ b/pkg/counter/doc.go @@ -21,7 +21,6 @@ Example Usage: // Create a Redis-backed counter redisCounter, err := counter.NewRedis(counter.RedisConfig{ RedisURL: "redis://localhost:6379", - Logger: logger, }) if err != nil { return err diff --git a/pkg/counter/interface.go b/pkg/counter/interface.go index f519346640..4afa666da5 100644 --- a/pkg/counter/interface.go +++ b/pkg/counter/interface.go @@ -153,7 +153,7 @@ type Counter interface { // // func LoggingMiddleware(logger Logger) Middleware { // return func(next Counter) Counter { -// return &loggingCounter{next: next, logger: logger} +// return &loggingCounter{next: next} // } // } type Middleware func(Counter) Counter diff --git a/pkg/counter/redis.go b/pkg/counter/redis.go index a1b9b1b6b8..b0a788a6ac 100644 --- a/pkg/counter/redis.go +++ b/pkg/counter/redis.go @@ -8,7 +8,7 @@ import ( "github.com/redis/go-redis/v9" "github.com/unkeyed/unkey/pkg/assert" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" ) @@ -56,9 +56,6 @@ var ( type redisCounter struct { // redis is the Redis client redis *redis.Client - - // logger for logging - logger logging.Logger } var _ Counter = (*redisCounter)(nil) @@ -68,10 +65,6 @@ type RedisConfig struct { // RedisURL is the connection URL for Redis. // Format: redis://[[username][:password]@][host][:port][/database] RedisURL string - - // Logger is the logging implementation to use. - // Optional, but recommended for production use. - Logger logging.Logger } // NewRedis creates a new Redis-backed counter implementation. @@ -85,7 +78,6 @@ type RedisConfig struct { func NewRedis(config RedisConfig) (Counter, error) { err := assert.All( assert.NotEmpty(config.RedisURL, "Redis URL must not be empty"), - assert.NotNil(config.Logger, "Logger must not be nil"), ) if err != nil { return nil, err @@ -97,7 +89,7 @@ func NewRedis(config RedisConfig) (Counter, error) { } rdb := redis.NewClient(opts) - config.Logger.Debug("pinging redis") + logger.Debug("pinging redis") // Test connection _, err = rdb.Ping(context.Background()).Result() @@ -106,8 +98,7 @@ func NewRedis(config RedisConfig) (Counter, error) { } return &redisCounter{ - redis: rdb, - logger: config.Logger, + redis: rdb, }, nil } @@ -138,7 +129,7 @@ func (r *redisCounter) Increment(ctx context.Context, key string, value int64, t // set the expiration time if len(ttl) > 0 && newValue == value { if err := r.redis.Expire(ctx, key, ttl[0]).Err(); err != nil { - r.logger.Error("failed to set TTL on counter", "key", key, "error", err.Error()) + logger.Error("failed to set TTL on counter", "key", key, "error", err.Error()) // We don't return the error since the increment operation was successful } } @@ -187,7 +178,7 @@ func (r *redisCounter) Decrement(ctx context.Context, key string, value int64, t // set the expiration time if len(ttl) > 0 && newValue == -value { if err := r.redis.Expire(ctx, key, ttl[0]).Err(); err != nil { - r.logger.Error("failed to set TTL on counter", "key", key, "error", err.Error()) + logger.Error("failed to set TTL on counter", "key", key, "error", err.Error()) // We don't return the error since the decrement operation was successful } } @@ -337,7 +328,7 @@ func (r *redisCounter) MultiGet(ctx context.Context, keys []string) (map[string] s, ok := values[i].(string) if !ok { - r.logger.Warn("unexpected type for counter value", + logger.Warn("unexpected type for counter value", "key", key, "type", fmt.Sprintf("%T", values[i]), ) @@ -345,7 +336,7 @@ func (r *redisCounter) MultiGet(ctx context.Context, keys []string) (map[string] } v, err := strconv.ParseInt(s, 10, 64) if err != nil { - r.logger.Warn("failed to parse counter value", + logger.Warn("failed to parse counter value", "key", key, "value", s, "error", err, diff --git a/pkg/counter/redis_test.go b/pkg/counter/redis_test.go index 96ede65fe4..8cd078aa16 100644 --- a/pkg/counter/redis_test.go +++ b/pkg/counter/redis_test.go @@ -9,7 +9,6 @@ import ( "github.com/stretchr/testify/require" "github.com/unkeyed/unkey/pkg/dockertest" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/uid" ) @@ -20,7 +19,6 @@ func TestRedisCounter(t *testing.T) { // Create a Redis counter ctr, err := NewRedis(RedisConfig{ RedisURL: redisURL, - Logger: logging.New(), }) require.NoError(t, err) defer func() { require.NoError(t, ctr.Close()) }() @@ -299,7 +297,6 @@ func TestRedisCounterConnection(t *testing.T) { // Test with invalid URL _, err := NewRedis(RedisConfig{ RedisURL: "invalid://url", - Logger: logging.New(), }) require.Error(t, err) }) @@ -308,7 +305,6 @@ func TestRedisCounterConnection(t *testing.T) { // Test with non-existent Redis server _, err := NewRedis(RedisConfig{ RedisURL: "redis://localhost:12345", - Logger: logging.New(), }) require.Error(t, err) }) @@ -317,7 +313,6 @@ func TestRedisCounterConnection(t *testing.T) { // Test with empty URL _, err := NewRedis(RedisConfig{ RedisURL: "", - Logger: logging.New(), }) require.Error(t, err) }) @@ -330,7 +325,6 @@ func TestRedisCounterMultiGet(t *testing.T) { // Create a Redis counter ctr, err := NewRedis(RedisConfig{ RedisURL: redisURL, - Logger: logging.New(), }) require.NoError(t, err) defer func() { require.NoError(t, ctr.Close()) }() @@ -452,7 +446,6 @@ func TestRedisCounterDecrement(t *testing.T) { // Create a Redis counter ctr, err := NewRedis(RedisConfig{ RedisURL: redisURL, - Logger: logging.New(), }) require.NoError(t, err) defer func() { require.NoError(t, ctr.Close()) }() @@ -544,7 +537,6 @@ func TestRedisCounterDecrementIfExists(t *testing.T) { // Create a Redis counter ctr, err := NewRedis(RedisConfig{ RedisURL: redisURL, - Logger: logging.New(), }) require.NoError(t, err) defer func() { require.NoError(t, ctr.Close()) }() @@ -651,12 +643,10 @@ func TestRedisCounterDecrementIfExists(t *testing.T) { // TestRedisCounterDelete tests the Delete operation on the Redis counter. func TestRedisCounterDelete(t *testing.T) { ctx := context.Background() - logger := logging.New() redisURL := dockertest.Redis(t) ctr, err := NewRedis(RedisConfig{ RedisURL: redisURL, - Logger: logger, }) require.NoError(t, err) defer func() { require.NoError(t, ctr.Close()) }() @@ -731,12 +721,10 @@ func TestRedisCounterDelete(t *testing.T) { // TestRedisCounterDecrementLogic tests the decrement logic that avoids negative values func TestRedisCounterDecrementLogic(t *testing.T) { ctx := context.Background() - logger := logging.New() redisURL := dockertest.Redis(t) ctr, err := NewRedis(RedisConfig{ RedisURL: redisURL, - Logger: logger, }) require.NoError(t, err) defer func() { require.NoError(t, ctr.Close()) }() diff --git a/pkg/db/BUILD.bazel b/pkg/db/BUILD.bazel index 5337ed0e12..041fb24484 100644 --- a/pkg/db/BUILD.bazel +++ b/pkg/db/BUILD.bazel @@ -280,7 +280,7 @@ go_library( "//pkg/codes", "//pkg/db/types", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/otel/tracing", "//pkg/prometheus/metrics", "//pkg/retry", @@ -299,7 +299,6 @@ go_test( embed = [":db"], deps = [ "//pkg/hash", - "//pkg/otel/logging", "//pkg/testutil/containers", "//pkg/uid", "@com_github_go_sql_driver_mysql//:mysql", diff --git a/pkg/db/database.go b/pkg/db/database.go index c06d21758a..145a2d033c 100644 --- a/pkg/db/database.go +++ b/pkg/db/database.go @@ -10,7 +10,7 @@ import ( "github.com/unkeyed/unkey/pkg/assert" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/retry" ) @@ -24,20 +24,16 @@ type Config struct { // The readonly replica will be used for most read queries. // If omitted, the primary is used. ReadOnlyDSN string - - // Logger for database-related operations - Logger logging.Logger } // database implements the Database interface, providing access to database replicas // and handling connection lifecycle. type database struct { - writeReplica *Replica // Primary database connection used for write operations - readReplica *Replica // Connection used for read operations (may be same as primary) - logger logging.Logger // Logger for database operations + writeReplica *Replica // Primary database connection used for write operations + readReplica *Replica // Connection used for read operations (may be same as primary) } -func open(dsn string, logger logging.Logger) (db *sql.DB, err error) { +func open(dsn string) (db *sql.DB, err error) { if !strings.Contains(dsn, "parseTime=true") { return nil, fault.New("DSN must contain parseTime=true, see https://stackoverflow.com/questions/29341590/how-to-parse-time-from-database/29343013#29343013") } @@ -86,14 +82,13 @@ func open(dsn string, logger logging.Logger) (db *sql.DB, err error) { // Returns an error if connections cannot be established or if DSNs are misconfigured. func New(config Config) (*database, error) { err := assert.All( - assert.NotNil(config.Logger), assert.NotEmpty(config.PrimaryDSN), ) if err != nil { return nil, fault.Wrap(err, fault.Internal("invalid configuration")) } - write, err := open(config.PrimaryDSN, config.Logger) + write, err := open(config.PrimaryDSN) if err != nil { return nil, fault.Wrap(err, fault.Internal("cannot open primary replica")) } @@ -102,7 +97,6 @@ func New(config Config) (*database, error) { writeReplica := &Replica{ db: write, mode: "rw", - logger: config.Logger, debugLogs: false, } @@ -110,13 +104,12 @@ func New(config Config) (*database, error) { readReplica := &Replica{ db: write, mode: "rw", - logger: config.Logger, debugLogs: false, } // If a separate read-only DSN is provided, establish that connection if config.ReadOnlyDSN != "" { - read, err := open(config.ReadOnlyDSN, config.Logger) + read, err := open(config.ReadOnlyDSN) if err != nil { return nil, fault.Wrap(err, fault.Internal("cannot open read replica")) } @@ -124,18 +117,16 @@ func New(config Config) (*database, error) { readReplica = &Replica{ db: read, mode: "ro", - logger: config.Logger, debugLogs: false, } - config.Logger.Info("database configured with separate read replica") + logger.Info("database configured with separate read replica") } else { - config.Logger.Info("database configured without separate read replica, using primary for reads") + logger.Info("database configured without separate read replica, using primary for reads") } return &database{ writeReplica: writeReplica, readReplica: readReplica, - logger: config.Logger, }, nil } diff --git a/pkg/db/doc.go b/pkg/db/doc.go index 8f0c81dbcf..508e503cdb 100644 --- a/pkg/db/doc.go +++ b/pkg/db/doc.go @@ -18,7 +18,6 @@ // db, err := db.New(db.Config{ // PrimaryDSN: "mysql://user:pass@primary:3306/dbname?parseTime=true", // ReadOnlyDSN: "mysql://user:pass@replica:3306/dbname?parseTime=true", -// Logger: logger, // }) // if err != nil { // return fmt.Errorf("database initialization failed: %w", err) diff --git a/pkg/db/replica.go b/pkg/db/replica.go index 830df9fbab..2ca5dcfaae 100644 --- a/pkg/db/replica.go +++ b/pkg/db/replica.go @@ -7,7 +7,7 @@ import ( "database/sql" "time" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" "github.com/unkeyed/unkey/pkg/prometheus/metrics" "go.opentelemetry.io/otel/attribute" @@ -18,7 +18,6 @@ import ( type Replica struct { mode string db *sql.DB // Underlying database connection - logger logging.Logger debugLogs bool } @@ -36,7 +35,7 @@ func (r *Replica) ExecContext(ctx context.Context, query string, args ...any) (s ) if r.debugLogs { - r.logger.Debug("ExecContext", "query", query) + logger.Debug("ExecContext", "query", query) } // Track metrics @@ -67,7 +66,7 @@ func (r *Replica) PrepareContext(ctx context.Context, query string) (*sql.Stmt, ) if r.debugLogs { - r.logger.Debug("PrepareContext", "query", query) + logger.Debug("PrepareContext", "query", query) } // Track metrics @@ -99,7 +98,7 @@ func (r *Replica) QueryContext(ctx context.Context, query string, args ...any) ( ) if r.debugLogs { - r.logger.Debug("QueryContext", "query", query) + logger.Debug("QueryContext", "query", query) } // Track metrics @@ -131,7 +130,7 @@ func (r *Replica) QueryRowContext(ctx context.Context, query string, args ...any ) if r.debugLogs { - r.logger.Debug("QueryRowContext", "query", query) + logger.Debug("QueryRowContext", "query", query) } // Track metrics start := time.Now() diff --git a/pkg/db/retry_test.go b/pkg/db/retry_test.go index c7a5d0be6f..cc8d3b3de7 100644 --- a/pkg/db/retry_test.go +++ b/pkg/db/retry_test.go @@ -9,7 +9,6 @@ import ( "github.com/go-sql-driver/mysql" "github.com/stretchr/testify/require" "github.com/unkeyed/unkey/pkg/hash" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/pkg/uid" ) @@ -209,7 +208,6 @@ func TestWithRetryContext_Integration(t *testing.T) { // Create database instance dbInstance, err := New(Config{ PrimaryDSN: mysqlCfg.FormatDSN(), - Logger: logging.NewNoop(), }) require.NoError(t, err) defer func() { require.NoError(t, dbInstance.Close()) }() diff --git a/pkg/eventstream/BUILD.bazel b/pkg/eventstream/BUILD.bazel index b20cf01d8c..0295152808 100644 --- a/pkg/eventstream/BUILD.bazel +++ b/pkg/eventstream/BUILD.bazel @@ -14,7 +14,7 @@ go_library( visibility = ["//visibility:public"], deps = [ "//pkg/assert", - "//pkg/otel/logging", + "//pkg/logger", "@com_github_segmentio_kafka_go//:kafka-go", "@org_golang_google_protobuf//proto", ], @@ -27,7 +27,6 @@ go_test( deps = [ ":eventstream", "//gen/proto/cache/v1:cache", - "//pkg/otel/logging", "//pkg/testutil/containers", "//pkg/uid", "@com_github_stretchr_testify//require", diff --git a/pkg/eventstream/consumer.go b/pkg/eventstream/consumer.go index 7f05bb2f7e..bb10ecc7f5 100644 --- a/pkg/eventstream/consumer.go +++ b/pkg/eventstream/consumer.go @@ -10,7 +10,7 @@ import ( "time" "github.com/segmentio/kafka-go" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "google.golang.org/protobuf/proto" ) @@ -26,7 +26,6 @@ type consumer[T proto.Message] struct { handler func(context.Context, T) error reader *kafka.Reader instanceID string - logger logging.Logger mu sync.Mutex subscribed bool fromBeginning bool @@ -94,7 +93,6 @@ func (t *Topic[T]) NewConsumer(opts ...ConsumerOption) Consumer[T] { brokers: t.brokers, topic: t.topic, instanceID: t.instanceID, - logger: t.logger, fromBeginning: cfg.fromBeginning, isPointerType: isPointerType, } @@ -218,7 +216,7 @@ func (c *consumer[T]) consumeLoop(ctx context.Context) { // EOF is expected when there are no more messages - don't log it if !isEOF(err) { - c.logger.Warn("Failed to read message from Kafka", "error", err.Error(), "topic", c.topic) + logger.Warn("Failed to read message from Kafka", "error", err.Error(), "topic", c.topic) } continue @@ -233,14 +231,14 @@ func (c *consumer[T]) consumeLoop(ctx context.Context) { var ok bool t, ok = newInstance.(T) if !ok { - c.logger.Error("Failed to cast reflected type to expected type", "topic", c.topic) + logger.Error("Failed to cast reflected type to expected type", "topic", c.topic) continue } } // Deserialize protobuf event if err := proto.Unmarshal(msg.Value, t); err != nil { - c.logger.Warn("Failed to deserialize protobuf message", "error", err.Error(), "topic", c.topic) + logger.Warn("Failed to deserialize protobuf message", "error", err.Error(), "topic", c.topic) continue } @@ -248,7 +246,7 @@ func (c *consumer[T]) consumeLoop(ctx context.Context) { if c.handler != nil { handlerCtx, cancel := context.WithTimeout(ctx, 30*time.Second) if err := c.handler(handlerCtx, t); err != nil { - c.logger.Error("Error handling event", "error", err.Error(), "topic", c.topic) + logger.Error("Error handling event", "error", err.Error(), "topic", c.topic) } cancel() } diff --git a/pkg/eventstream/doc.go b/pkg/eventstream/doc.go index 30a4120fe0..11a56d96a6 100644 --- a/pkg/eventstream/doc.go +++ b/pkg/eventstream/doc.go @@ -18,12 +18,10 @@ // // Basic event streaming setup: // -// logger := logging.NewLogger() // topic := eventstream.NewTopic[*MyEvent](eventstream.TopicConfig{ // Brokers: []string{"kafka:9092"}, // Topic: "my-events", // InstanceID: "instance-1", -// Logger: logger, // }) // // // Publishing events diff --git a/pkg/eventstream/eventstream_integration_test.go b/pkg/eventstream/eventstream_integration_test.go index 95b0ae41d1..e9cd9cd8ae 100644 --- a/pkg/eventstream/eventstream_integration_test.go +++ b/pkg/eventstream/eventstream_integration_test.go @@ -11,7 +11,6 @@ import ( "github.com/stretchr/testify/require" cachev1 "github.com/unkeyed/unkey/gen/proto/cache/v1" "github.com/unkeyed/unkey/pkg/eventstream" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/pkg/uid" ) @@ -25,14 +24,10 @@ func TestEventStreamIntegration(t *testing.T) { topicName := fmt.Sprintf("test-eventstream-%s", uid.New(uid.TestPrefix)) instanceID := uid.New(uid.TestPrefix) - // Use real logger to see what's happening - logger := logging.New() - config := eventstream.TopicConfig{ Brokers: brokers, Topic: topicName, InstanceID: instanceID, - Logger: logger, } t.Logf("Test config: topic=%s, instanceID=%s, brokers=%v", topicName, instanceID, brokers) @@ -124,7 +119,6 @@ func TestEventStreamMultipleMessages(t *testing.T) { Brokers: brokers, Topic: topicName, InstanceID: uid.New(uid.TestPrefix), - Logger: logging.NewNoop(), } topic, err := eventstream.NewTopic[*cachev1.CacheInvalidationEvent](config) diff --git a/pkg/eventstream/noop.go b/pkg/eventstream/noop.go index 13a8f08a51..daeaa1d029 100644 --- a/pkg/eventstream/noop.go +++ b/pkg/eventstream/noop.go @@ -52,7 +52,6 @@ func NewNoopTopic[T proto.Message]() *Topic[T] { brokers: nil, topic: "", instanceID: "", - logger: nil, consumers: nil, producers: nil, } diff --git a/pkg/eventstream/producer.go b/pkg/eventstream/producer.go index 5ee2e3200f..8818aacbc6 100644 --- a/pkg/eventstream/producer.go +++ b/pkg/eventstream/producer.go @@ -5,7 +5,7 @@ import ( "time" "github.com/segmentio/kafka-go" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "google.golang.org/protobuf/proto" ) @@ -14,7 +14,6 @@ type producer[T proto.Message] struct { writer *kafka.Writer instanceID string topic string - logger logging.Logger } // NewProducer creates a new producer for publishing events to this topic. @@ -61,7 +60,6 @@ func (t *Topic[T]) NewProducer() Producer[T] { }, instanceID: t.instanceID, topic: t.topic, - logger: t.logger, } // Track producer for cleanup @@ -134,7 +132,7 @@ func (p *producer[T]) Produce(ctx context.Context, events ...T) error { // Serialize event to protobuf data, err := proto.Marshal(event) if err != nil { - p.logger.Error("Failed to serialize event", "error", err.Error(), "topic", p.topic, "event_index", i) + logger.Error("Failed to serialize event", "error", err.Error(), "topic", p.topic, "event_index", i) return err } @@ -153,7 +151,7 @@ func (p *producer[T]) Produce(ctx context.Context, events ...T) error { // Publish all messages in a single batch err := p.writer.WriteMessages(ctx, messages...) if err != nil { - p.logger.Error("Failed to publish events to Kafka", "error", err.Error(), "topic", p.topic, "event_count", len(events)) + logger.Error("Failed to publish events to Kafka", "error", err.Error(), "topic", p.topic, "event_count", len(events)) return err } diff --git a/pkg/eventstream/topic.go b/pkg/eventstream/topic.go index 8694697e35..a79c91107b 100644 --- a/pkg/eventstream/topic.go +++ b/pkg/eventstream/topic.go @@ -8,7 +8,7 @@ import ( "github.com/segmentio/kafka-go" "github.com/unkeyed/unkey/pkg/assert" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "google.golang.org/protobuf/proto" ) @@ -22,9 +22,6 @@ type TopicConfig struct { // InstanceID is a unique identifier for this instance in the cluster. InstanceID string - - // Logger is used for logging events and errors. - Logger logging.Logger } // Topic provides access to producers and consumers for a specific topic @@ -32,7 +29,6 @@ type Topic[T proto.Message] struct { brokers []string topic string instanceID string - logger logging.Logger // Track consumers and producers for cleanup mu sync.Mutex @@ -52,13 +48,11 @@ type Topic[T proto.Message] struct { // Brokers: []string{"kafka:9092"}, // Topic: "events", // InstanceID: "instance-1", -// Logger: logger, // } // topic := eventstream.NewTopic[*MyEvent](cfg) func NewTopic[T proto.Message](config TopicConfig) (*Topic[T], error) { // Validate required fields err := assert.All( - assert.NotNilAndNotZero(config.Logger, "logger is required when creating a topic"), assert.True(len(config.Brokers) > 0, "brokers list cannot be empty"), assert.NotEmpty(config.Topic, "topic name cannot be empty"), assert.NotEmpty(config.InstanceID, "instance ID cannot be empty"), @@ -74,7 +68,6 @@ func NewTopic[T proto.Message](config TopicConfig) (*Topic[T], error) { brokers: config.Brokers, topic: config.Topic, instanceID: config.InstanceID, - logger: config.Logger, } return topic, nil @@ -240,9 +233,7 @@ func (t *Topic[T]) Close() error { // Close all consumers for _, consumer := range t.consumers { if err := consumer.Close(); err != nil { - if t.logger != nil { - t.logger.Error("Failed to close consumer", "error", err, "topic", t.topic) - } + logger.Error("Failed to close consumer", "error", err, "topic", t.topic) lastErr = err } } @@ -250,9 +241,7 @@ func (t *Topic[T]) Close() error { // Close all producers for _, producer := range t.producers { if err := producer.Close(); err != nil { - if t.logger != nil { - t.logger.Error("Failed to close producer", "error", err, "topic", t.topic) - } + logger.Error("Failed to close producer", "error", err, "topic", t.topic) lastErr = err } } diff --git a/pkg/logger/BUILD.bazel b/pkg/logger/BUILD.bazel new file mode 100644 index 0000000000..9d8e1ed864 --- /dev/null +++ b/pkg/logger/BUILD.bazel @@ -0,0 +1,17 @@ +load("@rules_go//go:def.bzl", "go_library") + +go_library( + name = "logger", + srcs = [ + "doc.go", + "event.go", + "global.go", + "multihandler.go", + "sampler.go", + "slog.go", + "wide.go", + ], + importpath = "github.com/unkeyed/unkey/pkg/logger", + visibility = ["//visibility:public"], + deps = ["//pkg/fault"], +) diff --git a/pkg/logger/doc.go b/pkg/logger/doc.go new file mode 100644 index 0000000000..9249cced2f --- /dev/null +++ b/pkg/logger/doc.go @@ -0,0 +1,61 @@ +// Package logger provides wide-event logging with tail sampling support. +// +// Traditional logging emits entries as they happen, scattering request context +// across many lines. Wide-event logging takes a different approach: it collects +// attributes throughout a request's lifecycle and emits a single, rich log entry +// at the end. This reduces log volume while preserving full context for debugging. +// +// The package is designed for request-scoped logging where you want to accumulate +// data across multiple function calls without threading a logger through every layer. +// +// # Key Types +// +// [Event] accumulates attributes and errors throughout a request. Create one with +// [Start], add data with [Set] or [SetError], and emit it with [End]. +// +// [Sampler] controls which events are emitted. Use [AlwaysSample] during development +// and [TailSampler] in production to reduce volume while preserving errors and slow +// requests. +// +// [MultiHandler] fans out log records to multiple [slog.Handler] implementations, +// enabling simultaneous output to console and structured backends. +// +// # Usage +// +// Start an event at the beginning of a request, add attributes as you process, +// and end it when done: +// +// ctx, event := logger.Start(ctx, slog.String("handler", "createKey")) +// defer logger.End(ctx) +// +// logger.Set(ctx, slog.String("userId", user.ID)) +// if err != nil { +// logger.SetError(ctx, err) +// return err +// } +// +// The event is stored in the context, so any function with access to ctx can add +// attributes without needing a reference to the event itself. +// +// # Tail Sampling +// +// Tail sampling decides whether to emit a log after t pgit puthe request completes, rather +// than at the start. This allows sampling decisions based on outcome: always log +// errors and slow requests, sample routine successes at a lower rate. +// +// logger.SetSampler(logger.TailSampler{ +// SlowThreshold: time.Second, // always log slow requests +// SampleRate: 0.1, // sample 10% of normal requests +// }) +// +// # Standalone Logging +// +// For logs outside request context, use the standard level functions [Debug], [Info], +// [Warn], and [Error]. These bypass the wide-event system and log immediately. +// +// # Configuration +// +// Use [AddHandler] to add additional log destinations, [AddBaseAttrs] to include +// attributes in all logs, and [SetSampler] to configure sampling behavior. The +// package defaults to [slog.Default] with [AlwaysSample]. +package logger diff --git a/pkg/logger/event.go b/pkg/logger/event.go new file mode 100644 index 0000000000..2d57b27b7c --- /dev/null +++ b/pkg/logger/event.go @@ -0,0 +1,106 @@ +package logger + +import ( + "fmt" + "log/slog" + "sync" + "time" + + "github.com/unkeyed/unkey/pkg/fault" +) + +// eventKey is the context key for storing wide events. +type eventKey struct{} + +// Event accumulates attributes and errors throughout a request lifecycle, +// emitting a single log entry when [End] is called. This "wide event" pattern +// reduces log volume while preserving full context for debugging. +// +// Safe for concurrent use. Multiple goroutines can call [Event.Add] and +// [Event.SetError] on the same event. +type Event struct { + mu sync.Mutex + start time.Time + duration time.Duration + message string + attrs []slog.Attr + errors []error + written bool +} + +// Add appends attributes to the event. These attributes will be included +// in the log entry when [End] is called. Prefer using the context-based +// [Set] function when possible, as it doesn't require passing the event directly. +func (e *Event) Add(attrs ...slog.Attr) { + e.mu.Lock() + defer e.mu.Unlock() + e.attrs = append(e.attrs, attrs...) +} + +// Set is an alias for [Event.Add], provided for consistency with the +// package-level [Set] function. +func (e *Event) Set(attrs ...slog.Attr) { + e.Add(attrs...) +} + +// SetError records an error on the event. Multiple errors can be recorded +// and will appear as "error-0", "error-1", etc. in the log output. Nil +// errors are silently ignored, so callers don't need to check before calling. +// +// Events with errors are logged at error level when [End] is called. +func (e *Event) SetError(err error) { + if err == nil { + return + } + e.mu.Lock() + defer e.mu.Unlock() + + e.errors = append(e.errors, err) +} + +// End emits the accumulated event as a log entry if the configured [Sampler] +// allows it. Events with errors are logged at error level; others at info level. +// +// Safe to call multiple times; only the first call emits a log entry. Subsequent +// calls are no-ops. Typically called via defer immediately after [StartWideEvent]. +func (e *Event) End() { + e.mu.Lock() + defer e.mu.Unlock() + if e.written { + return + } + e.written = true + + if !sampler.Sample(e) { + return + } + + errors := []slog.Attr{} + for i, err := range e.errors { + code, _ := fault.GetCode(err) + errors = append(errors, slog.Group(fmt.Sprintf("%d", i), + slog.String("internal", fault.InternalMessage(err)), + slog.String("public", fault.UserFacingMessage(err)), + slog.String("code", string(code)), + slog.Any("steps", fault.Flatten(err)), + )) + } + + casted := []any{ + slog.GroupAttrs("errors", errors...), + slog.GroupAttrs("log_meta", + slog.Time("start", e.start), + slog.Duration("duration", time.Since(e.start)), + ), + } + for _, attr := range e.attrs { + casted = append(casted, attr) + } + + if len(e.errors) > 0 { + logger.Error("error", casted...) + } else { + logger.Info(e.message, casted...) + } + +} diff --git a/pkg/logger/global.go b/pkg/logger/global.go new file mode 100644 index 0000000000..6a8f4ac4f7 --- /dev/null +++ b/pkg/logger/global.go @@ -0,0 +1,66 @@ +package logger + +import ( + "log/slog" + "sync" +) + +// Package-level state for the global logger, sampler, and base attributes. +// Protected by mu for concurrent access during configuration. +var ( + logger *slog.Logger + sampler Sampler + mu sync.Mutex +) + +func init() { + mu = sync.Mutex{} + logger = slog.Default() + sampler = AlwaysSample{} +} + +// GetHandler returns the current [slog.Handler] used by the global logger. +// This can be used to inspect or wrap the handler for custom behavior. +// +// Safe for concurrent use. +func GetHandler() slog.Handler { + mu.Lock() + defer mu.Unlock() + return logger.Handler() +} + +// AddHandler registers an additional [slog.Handler] to receive log records. +// Handlers are composed using [MultiHandler], so each log entry is sent to +// all registered handlers. This enables simultaneous output to multiple +// destinations like console and a structured logging backend. +// +// Safe for concurrent use. Handlers added after logging has started will +// receive all subsequent log entries. +func AddHandler(newHandler slog.Handler) { + mu.Lock() + defer mu.Unlock() + logger = slog.New(&MultiHandler{[]slog.Handler{logger.Handler(), newHandler}}) +} + +// AddBaseAttrs appends attributes that will be included in every log entry. +// Use this to add service-level context like version, environment, or instance ID. +// +// Safe for concurrent use. Attributes are appended, not replaced, so multiple +// calls accumulate. +func AddBaseAttrs(attrs ...slog.Attr) { + mu.Lock() + defer mu.Unlock() + logger = slog.New(logger.Handler().WithAttrs(attrs)) +} + +// SetSampler configures the sampling strategy for wide events. The sampler +// is consulted when [End] is called to decide whether to emit the log entry. +// Use [AlwaysSample] for development and [TailSampler] for production. +// +// Safe for concurrent use. Changing the sampler affects all subsequent calls +// to [End], but does not affect events already in progress. +func SetSampler(s Sampler) { + mu.Lock() + defer mu.Unlock() + sampler = s +} diff --git a/pkg/otel/logging/multi.go b/pkg/logger/multihandler.go similarity index 57% rename from pkg/otel/logging/multi.go rename to pkg/logger/multihandler.go index e8906fa54a..ce017fa481 100644 --- a/pkg/otel/logging/multi.go +++ b/pkg/logger/multihandler.go @@ -1,4 +1,4 @@ -package logging +package logger import ( "context" @@ -6,12 +6,19 @@ import ( "log/slog" ) +// MultiHandler fans out log records to multiple [slog.Handler] implementations. +// Use this to send logs to multiple destinations simultaneously, such as +// console output and a structured logging backend. +// +// A record is handled by all handlers that are enabled for that record's level. +// Errors from individual handlers are collected and returned as a joined error. type MultiHandler struct { Handlers []slog.Handler } var _ slog.Handler = (*MultiHandler)(nil) +// Enabled returns true if any handler is enabled for the given level. func (h *MultiHandler) Enabled(ctx context.Context, level slog.Level) bool { for _, handler := range h.Handlers { if handler.Enabled(ctx, level) { @@ -21,6 +28,9 @@ func (h *MultiHandler) Enabled(ctx context.Context, level slog.Level) bool { return false } +// Handle passes the record to all handlers that are enabled for its level. +// Returns a joined error if any handlers fail; handlers that succeed are +// not affected by failures in other handlers. func (h *MultiHandler) Handle(ctx context.Context, record slog.Record) error { var errs []error for _, handler := range h.Handlers { @@ -37,22 +47,22 @@ func (h *MultiHandler) Handle(ctx context.Context, record slog.Record) error { return nil } +// WithAttrs returns a new MultiHandler with the given attributes added to +// all child handlers. func (h *MultiHandler) WithAttrs(attrs []slog.Attr) slog.Handler { - newHandlers := make([]slog.Handler, len(h.Handlers)) for i := range h.Handlers { newHandlers[i] = h.Handlers[i].WithAttrs(attrs) } return &MultiHandler{newHandlers} - } +// WithGroup returns a new MultiHandler with the given group name added to +// all child handlers. func (h *MultiHandler) WithGroup(name string) slog.Handler { - newHandlers := make([]slog.Handler, len(h.Handlers)) for i := range h.Handlers { newHandlers[i] = h.Handlers[i].WithGroup(name) } return &MultiHandler{newHandlers} - } diff --git a/pkg/logger/sampler.go b/pkg/logger/sampler.go new file mode 100644 index 0000000000..1b6e7b34ef --- /dev/null +++ b/pkg/logger/sampler.go @@ -0,0 +1,63 @@ +package logger + +import ( + "math/rand/v2" + "time" +) + +// Sampler decides whether an event should be emitted when [End] is called. +// Implementations can inspect the completed event to make sampling decisions +// based on outcome, enabling tail sampling strategies. +type Sampler interface { + Sample(event *Event) bool +} + +// AlwaysSample emits every event unconditionally. Use during development +// or debugging when you need to see all log output. Not recommended for +// production due to log volume. +type AlwaysSample struct{} + +// Sample always returns true, emitting every event. +func (AlwaysSample) Sample(*Event) bool { + return true +} + +// TailSampler provides probabilistic sampling with bias toward errors and +// slow requests. This is the recommended sampler for production: it reduces +// log volume for routine successes while ensuring errors and performance +// issues are always captured. +// +// Sampling rates are probabilities between 0.0 (never) and 1.0 (always). +// Events are evaluated in priority order: errors first, then slow requests, +// then baseline rate. An event matching multiple criteria (e.g., slow and +// has errors) is evaluated against the first matching rate. +type TailSampler struct { + + // SlowThreshold defines what duration qualifies as "slow". Events + // exceeding this duration are always sampled. + SlowThreshold time.Duration + + // SampleRate is the baseline probability for events that aren't errors + // and aren't slow. Set to 0.1 to sample 10% of normal traffic. + SampleRate float64 +} + +// Sample returns true if the event should be emitted based on configured rates. +// A single random value is generated and compared against each rate in order, +// so an event that matches multiple criteria still only has one chance to be +// sampled. +func (s TailSampler) Sample(event *Event) bool { + rate := rand.Float64() + + if len(event.errors) > 0 { + return true + } + + if event.duration > s.SlowThreshold { + return true + } + if rate < s.SampleRate { + return true + } + return false +} diff --git a/pkg/logger/slog.go b/pkg/logger/slog.go new file mode 100644 index 0000000000..24a6963288 --- /dev/null +++ b/pkg/logger/slog.go @@ -0,0 +1,30 @@ +package logger + +// Debug logs a message at debug level, bypassing the wide event system. +// Use for detailed diagnostic information during development. Arguments +// are key-value pairs in the same format as [slog.Logger.Debug]. +func Debug(msg string, args ...any) { + logger.Debug(msg, args...) +} + +// Info logs a message at info level, bypassing the wide event system. +// Use for notable events during normal operation. Arguments are key-value +// pairs in the same format as [slog.Logger.Info]. +func Info(msg string, args ...any) { + logger.Info(msg, args...) +} + +// Warn logs a message at warn level, bypassing the wide event system. +// Use for unexpected situations that aren't errors but may indicate problems. +// Arguments are key-value pairs in the same format as [slog.Logger.Warn]. +func Warn(msg string, args ...any) { + logger.Warn(msg, args...) +} + +// Error logs a message at error level, bypassing the wide event system. +// Use for failures that need attention. For request-scoped errors, prefer +// [SetError] to attach the error to the current wide event instead. +// Arguments are key-value pairs in the same format as [slog.Logger.Error]. +func Error(msg string, args ...any) { + logger.Error(msg, args...) +} diff --git a/pkg/logger/wide.go b/pkg/logger/wide.go new file mode 100644 index 0000000000..a8e95672d1 --- /dev/null +++ b/pkg/logger/wide.go @@ -0,0 +1,60 @@ +package logger + +import ( + "context" + "log/slog" + "sync" + "time" +) + +// StartWideEvent begins a new wide event and stores it in the returned context. +// The event records the start time for duration calculation and any initial +// attributes provided. +// +// The returned context should be passed to subsequent functions so they can +// add attributes via [Set]. Call [End] when the operation completes to emit +// the log entry based on the configured [Sampler]. +// +// Typical usage: +// +// ctx, event := logger.StartWideEvent(ctx, "incoming http request", slog.String("operation", "createKey")) +// defer event.End() +func StartWideEvent(ctx context.Context, message string, attrs ...slog.Attr) (context.Context, *Event) { + now := time.Now() + event := &Event{ + mu: sync.Mutex{}, + start: now, + duration: 0, + errors: []error{}, + message: message, + written: false, + attrs: attrs, + } + return context.WithValue(ctx, eventKey{}, event), event +} + +// Set adds attributes to the current event stored in the context. If no event +// exists (i.e., [Start] was never called), the call is silently ignored. This +// allows logging code to work safely in both request and non-request contexts. +func Set(ctx context.Context, attrs ...slog.Attr) { + event, ok := ctx.Value(eventKey{}).(*Event) + if !ok { + return + } + event.Add(attrs...) +} + +// SetError records an error on the current event. Multiple errors can be +// recorded and will appear as "error-0", "error-1", etc. in the log output. +// If no event exists in the context, the call is silently ignored. +// +// Events with errors are logged at error level when [End] is called and +// receive priority sampling when using [TailSampler]. +func SetError(ctx context.Context, err error) { + + event, ok := ctx.Value(eventKey{}).(*Event) + if !ok { + return + } + event.SetError(err) +} diff --git a/pkg/otel/BUILD.bazel b/pkg/otel/BUILD.bazel index 7a7f881571..1dc9cea917 100644 --- a/pkg/otel/BUILD.bazel +++ b/pkg/otel/BUILD.bazel @@ -10,7 +10,7 @@ go_library( importpath = "github.com/unkeyed/unkey/pkg/otel", visibility = ["//visibility:public"], deps = [ - "//pkg/otel/logging", + "//pkg/logger", "//pkg/otel/tracing", "//pkg/version", "@com_github_shirou_gopsutil_v4//cpu", diff --git a/pkg/otel/grafana.go b/pkg/otel/grafana.go index 5902b1206d..97e63e80cb 100644 --- a/pkg/otel/grafana.go +++ b/pkg/otel/grafana.go @@ -7,7 +7,7 @@ import ( "github.com/shirou/gopsutil/v4/cpu" "github.com/shirou/gopsutil/v4/mem" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" "github.com/unkeyed/unkey/pkg/version" "go.opentelemetry.io/contrib/bridges/otelslog" @@ -117,7 +117,7 @@ func InitGrafana(ctx context.Context, config Config) (func(ctx context.Context) log.WithProcessor(processor), ) - logging.AddHandler(otelslog.NewHandler( + logger.AddHandler(otelslog.NewHandler( config.Application, otelslog.WithLoggerProvider(logProvider), otelslog.WithVersion(version.Version), diff --git a/pkg/otel/logging/BUILD.bazel b/pkg/otel/logging/BUILD.bazel deleted file mode 100644 index 1a8359774f..0000000000 --- a/pkg/otel/logging/BUILD.bazel +++ /dev/null @@ -1,15 +0,0 @@ -load("@rules_go//go:def.bzl", "go_library") - -go_library( - name = "logging", - srcs = [ - "doc.go", - "interface.go", - "multi.go", - "noop.go", - "slog.go", - ], - importpath = "github.com/unkeyed/unkey/pkg/otel/logging", - visibility = ["//visibility:public"], - deps = ["@com_github_lmittmann_tint//:tint"], -) diff --git a/pkg/otel/logging/doc.go b/pkg/otel/logging/doc.go deleted file mode 100644 index 9247ec5668..0000000000 --- a/pkg/otel/logging/doc.go +++ /dev/null @@ -1,63 +0,0 @@ -// Package logging provides a flexible structured logging interface that follows -// the patterns of Go's standard slog package while abstracting over concrete -// logging implementations. -// -// The interface offers two styles of logging methods: -// -// 1. Standard methods (Debug, Info, Warn, Error) - without context but with -// simple key-value pairs as variadic arguments. -// 2. Context-aware methods (DebugContext, InfoContext, WarnContext, ErrorContext) - -// with context and structured slog.Attr values. -// -// This pattern matches slog's API design, making it familiar to Go developers. -// -// Example without context (simple key-value pairs): -// -// logger.Info("User registered", -// "user_id", userID, -// "email", email, -// "age", age, -// ) -// -// Example with context (structured attributes): -// -// logger.InfoContext(ctx, "User registered", -// slog.String("user_id", userID), -// slog.String("email", email), -// slog.Int("age", age), -// ) -// -// The package defines a common Logger interface and provides implementations for -// different environments (development, production) as well as a no-op logger for -// testing. -// -// Key features: -// - API mirroring Go's standard slog package -// - Context-aware and context-free logging methods -// - Structured logging for consistent, parseable logs -// - Leveled logging with Debug, Info, Warn, and Error levels -// - Support for log enrichment through With and WithAttrs methods -// -// Example usage: -// -// // Create a logger -// logger := logging.New(logging.Config{ -// Development: true, // Use human-readable format in development -// NoColor: false, // Use colors in development mode -// }) -// -// // Create derived logger with added fields -// userLogger := logger.With( -// "user_id", user.ID, -// "email", user.Email, -// ) -// -// // Standard logging -// userLogger.Info("Profile updated", "field", "avatar") -// -// // Context-aware logging with structured attributes -// userLogger.InfoContext(ctx, "Payment processed", -// slog.Int("amount", payment.Amount), -// slog.String("currency", payment.Currency), -// ) -package logging diff --git a/pkg/otel/logging/interface.go b/pkg/otel/logging/interface.go deleted file mode 100644 index 19abe68841..0000000000 --- a/pkg/otel/logging/interface.go +++ /dev/null @@ -1,74 +0,0 @@ -package logging - -import ( - "log/slog" -) - -// Logger defines a structured logging interface that follows the patterns -// of Go's standard slog package, with methods for both context-aware and -// context-free logging. -type Logger interface { - // With creates a new logger with the given attributes always attached - // to future log entries. This is useful for adding context that should - // appear in all subsequent logs. - // - // Example: - // requestLogger := logger.With( - // "request_id", requestID, - // "method", r.Method, - // ) - With(args ...any) Logger - - // WithAttrs creates a new logger with the given slog.Attr values always - // attached to future log entries. This provides more type safety and - // flexibility than the With method. - // - // Example: - // requestLogger := logger.WithAttrs( - // slog.String("request_id", requestID), - // slog.String("method", r.Method), - // ) - WithAttrs(attrs ...slog.Attr) Logger - - WithCallDepth(depth int) Logger - - // ---- Standard logging methods (without context) ---- - - // Debug logs a message at debug level with simple key-value pairs. - // Keys must be strings. - // - // Example: - // logger.Debug("Processing request payload", - // "size", len(payload), - // "content_type", contentType, - // ) - Debug(msg string, args ...any) - - // Info logs a message at info level with simple key-value pairs. - // - // Example: - // logger.Info("User authenticated", - // "user_id", user.ID, - // "auth_method", "password", - // ) - Info(msg string, args ...any) - - // Warn logs a message at warn level with simple key-value pairs. - // - // Example: - // logger.Warn("API rate limit approaching threshold", - // "client_id", clientID, - // "requests", count, - // "limit", limit, - // ) - Warn(msg string, args ...any) - - // Error logs a message at error level with simple key-value pairs. - // - // Example: - // logger.Error("Failed to process payment", - // "payment_id", paymentID, - // "error", err.Error(), - // ) - Error(msg string, args ...any) -} diff --git a/pkg/otel/logging/noop.go b/pkg/otel/logging/noop.go deleted file mode 100644 index 5929905174..0000000000 --- a/pkg/otel/logging/noop.go +++ /dev/null @@ -1,80 +0,0 @@ -package logging - -import ( - "context" - "log/slog" -) - -// noop implements a Logger that discards all log messages. -// It's useful for testing environments or when logging needs to be completely disabled. -type noop struct { -} - -// NewNoop creates a new no-op logger that discards all log messages. -// This is particularly useful in testing scenarios where logs would -// add noise to test output, or in benchmarks where logging overhead -// should be eliminated. -// -// Example: -// -// // In tests -// func TestSomething(t *testing.T) { -// // Use a no-op logger to keep test output clean -// logger := logging.NewNoop() -// service := myservice.New(myservice.Config{Logger: logger}) -// // ... -// } -func NewNoop() Logger { - return &noop{} -} - -// With returns the same noop logger, ignoring the arguments. -func (l *noop) With(args ...any) Logger { - return l -} - -// WithAttrs returns the same noop logger, ignoring the attributes. -func (l *noop) WithAttrs(attrs ...slog.Attr) Logger { - return l -} - -// ---- Standard logging no-op methods ---- - -// Debug is a no-op implementation that discards debug level messages. -func (l *noop) Debug(msg string, args ...any) { -} - -// Info is a no-op implementation that discards info level messages. -func (l *noop) Info(msg string, args ...any) { -} - -// Warn is a no-op implementation that discards warn level messages. -func (l *noop) Warn(msg string, args ...any) { -} - -// Error is a no-op implementation that discards error level messages. -func (l *noop) Error(msg string, args ...any) { -} - -// ---- Context-aware logging no-op methods ---- - -// DebugContext is a no-op implementation that discards debug level messages. -func (l *noop) DebugContext(ctx context.Context, msg string, attrs ...slog.Attr) { -} - -// InfoContext is a no-op implementation that discards info level messages. -func (l *noop) InfoContext(ctx context.Context, msg string, attrs ...slog.Attr) { -} - -// WarnContext is a no-op implementation that discards warn level messages. -func (l *noop) WarnContext(ctx context.Context, msg string, attrs ...slog.Attr) { -} - -// ErrorContext is a no-op implementation that discards error level messages. -func (l *noop) ErrorContext(ctx context.Context, msg string, attrs ...slog.Attr) { -} - -// WithCallDepth is a no-op implementation that discards call depth. -func (l *noop) WithCallDepth(depth int) Logger { - return l -} diff --git a/pkg/otel/logging/slog.go b/pkg/otel/logging/slog.go deleted file mode 100644 index 1bbf3c0b71..0000000000 --- a/pkg/otel/logging/slog.go +++ /dev/null @@ -1,140 +0,0 @@ -package logging - -import ( - "context" - "fmt" - "log/slog" - "os" - "runtime" - "time" - - "github.com/lmittmann/tint" -) - -var handler slog.Handler - -func init() { - level := slog.LevelInfo - if os.Getenv("DEBUG") != "" { - level = slog.LevelDebug - } - - handler = tint.NewHandler(os.Stdout, &tint.Options{ - AddSource: true, - Level: level, - ReplaceAttr: nil, - TimeFormat: time.StampMilli, - NoColor: false, - }) -} - -func AddHandler(h slog.Handler) { - handler = &MultiHandler{[]slog.Handler{handler, h}} -} - -func SetHandler(h slog.Handler) { - handler = h -} - -// Handler returns the current slog.Handler used by the logging package. -// This is useful for integrating with libraries that accept a slog.Handler. -func Handler() slog.Handler { - return handler -} - -// logSkip logs with correct source location by skipping wrapper frames -func (l *logger) logSkip(ctx context.Context, level slog.Level, msg string, args ...any) { - if !l.logger.Enabled(ctx, level) { - return - } - var pcs [1]uintptr - runtime.Callers(l.callDepth, pcs[:]) // skip [runtime.Callers, logSkip, wrapper] - r := slog.NewRecord(time.Now(), level, msg, pcs[0]) - r.Add(args...) - if err := l.logger.Handler().Handle(ctx, r); err != nil { - fmt.Fprintf(os.Stderr, "logging handler error: %v\n", err) - } -} - -// logger implements the Logger interface using Go's standard slog package. -type logger struct { - logger *slog.Logger - callDepth int -} - -// New creates a new logger with the specified configuration. -// The logger adapts its format based on the environment: -// - In development mode, it uses a human-readable format with optional colors -// - In production mode, it uses structured JSON format -// -// Example: -// -// // Development logger with colors -// devLogger := logging.New(logging.Config{ -// Development: true, -// NoColor: false, -// }) -// -// // Production JSON logger -// prodLogger := logging.New(logging.Config{ -// Development: false, -// }) -func New() Logger { - l := slog.New(handler) - return &logger{ - logger: l, - callDepth: 3, - } -} - -// With creates a new logger with the given key-value pairs always attached. -func (l *logger) With(args ...any) Logger { - return &logger{ - logger: l.logger.With(args...), - callDepth: l.callDepth, - } -} - -// WithAttrs creates a new logger with the given attributes always attached. -func (l *logger) WithAttrs(attrs ...slog.Attr) Logger { - anys := make([]any, len(attrs)) - for i, a := range attrs { - anys[i] = a - } - - return &logger{ - logger: l.logger.With(anys...), - callDepth: l.callDepth, - } -} - -// WithCallDepth creates a new logger with the given call depth always attached. -func (l *logger) WithCallDepth(depth int) Logger { - - return &logger{ - logger: l.logger, - callDepth: depth, - } -} - -// ---- Standard logging methods ---- - -// Debug logs a message at debug level with key-value pairs. -func (l *logger) Debug(msg string, args ...any) { - l.logSkip(context.Background(), slog.LevelDebug, msg, args...) -} - -// Info logs a message at info level with key-value pairs. -func (l *logger) Info(msg string, args ...any) { - l.logSkip(context.Background(), slog.LevelInfo, msg, args...) -} - -// Warn logs a message at warn level with key-value pairs. -func (l *logger) Warn(msg string, args ...any) { - l.logSkip(context.Background(), slog.LevelWarn, msg, args...) -} - -// Error logs a message at error level with key-value pairs. -func (l *logger) Error(msg string, args ...any) { - l.logSkip(context.Background(), slog.LevelError, msg, args...) -} diff --git a/pkg/prometheus/BUILD.bazel b/pkg/prometheus/BUILD.bazel index 982d308ca9..3260795c7f 100644 --- a/pkg/prometheus/BUILD.bazel +++ b/pkg/prometheus/BUILD.bazel @@ -9,7 +9,6 @@ go_library( importpath = "github.com/unkeyed/unkey/pkg/prometheus", visibility = ["//visibility:public"], deps = [ - "//pkg/otel/logging", "//pkg/zen", "@com_github_prometheus_client_golang//prometheus/promhttp", ], diff --git a/pkg/prometheus/server.go b/pkg/prometheus/server.go index c6914cfa32..74a60bc417 100644 --- a/pkg/prometheus/server.go +++ b/pkg/prometheus/server.go @@ -20,18 +20,9 @@ import ( "net/http" "github.com/prometheus/client_golang/prometheus/promhttp" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/zen" ) -// Config configures the Prometheus metrics server. -// It specifies dependencies needed for the server to function correctly. -type Config struct { - // Logger is used for recording operational events from the metrics server. - // This logger should be configured appropriately for your environment. - Logger logging.Logger -} - // New creates a zen server that exposes Prometheus metrics at the /metrics endpoint. // The server is configured to handle GET requests to the /metrics path using the // standard Prometheus HTTP handler, which serves metrics in a format that Prometheus @@ -51,9 +42,8 @@ type Config struct { // Example usage: // // // Create a dedicated metrics server -// logger := logging.New() // server, err := prometheus.New(prometheus.Config{ -// Logger: logger, +// , // }) // if err != nil { // log.Fatalf("Failed to create metrics server: %v", err) @@ -72,10 +62,9 @@ type Config struct { // // See [zen.New] for details on the underlying server creation. // See [promhttp.Handler] for details on the Prometheus metrics handler. -func New(config Config) (*zen.Server, error) { +func New() (*zen.Server, error) { z, err := zen.New(zen.Config{ MaxRequestBodySize: 0, - Logger: config.Logger, Flags: nil, TLS: nil, EnableH2C: false, diff --git a/pkg/runner/BUILD.bazel b/pkg/runner/BUILD.bazel index 119be8c465..fa44ccb271 100644 --- a/pkg/runner/BUILD.bazel +++ b/pkg/runner/BUILD.bazel @@ -8,7 +8,7 @@ go_library( ], importpath = "github.com/unkeyed/unkey/pkg/runner", visibility = ["//visibility:public"], - deps = ["//pkg/otel/logging"], + deps = ["//pkg/logger"], ) go_test( @@ -21,8 +21,5 @@ go_test( "runner_test.go", ], embed = [":runner"], - deps = [ - "//pkg/otel/logging", - "@com_github_stretchr_testify//require", - ], + deps = ["@com_github_stretchr_testify//require"], ) diff --git a/pkg/runner/concurrency_test.go b/pkg/runner/concurrency_test.go index 50801d9ca7..093bfa3b33 100644 --- a/pkg/runner/concurrency_test.go +++ b/pkg/runner/concurrency_test.go @@ -8,13 +8,12 @@ import ( "time" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // TestConcurrency_GoIgnoredDuringShutdown verifies that tasks cannot be // registered after shutdown has started. func TestConcurrency_GoIgnoredDuringShutdown(t *testing.T) { - r := New(logging.NewNoop()) + r := New() var taskRan atomic.Bool @@ -53,7 +52,7 @@ func TestConcurrency_GoIgnoredDuringShutdown(t *testing.T) { // TestConcurrency_Registration verifies that Go and Defer are safe for // concurrent use from multiple goroutines. func TestConcurrency_Registration(t *testing.T) { - r := New(logging.NewNoop()) + r := New() const numGoroutines = 10 const itemsPerGoroutine = 50 @@ -102,7 +101,7 @@ func TestConcurrency_Registration(t *testing.T) { // TestConcurrency_DeferIgnoredDuringShutdown verifies that Defer calls made // while shutdown is in progress are silently ignored. func TestConcurrency_DeferIgnoredDuringShutdown(t *testing.T) { - r := New(logging.NewNoop()) + r := New() registered := make(chan struct{}) r.DeferCtx(func(ctx context.Context) error { @@ -139,7 +138,7 @@ func TestConcurrency_DeferIgnoredDuringShutdown(t *testing.T) { // TestConcurrency_GoStartsImmediately verifies that Go() starts tasks immediately, // not when Run() is called. func TestConcurrency_GoStartsImmediately(t *testing.T) { - r := New(logging.NewNoop()) + r := New() started := make(chan struct{}) r.Go(func(ctx context.Context) error { diff --git a/pkg/runner/error_test.go b/pkg/runner/error_test.go index ae70cd6ad4..3cec706724 100644 --- a/pkg/runner/error_test.go +++ b/pkg/runner/error_test.go @@ -7,13 +7,12 @@ import ( "time" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // TestError_CleanupErrorReturned verifies that errors from cleanup handlers // are returned from Run. func TestError_CleanupErrorReturned(t *testing.T) { - r := New(logging.NewNoop()) + r := New() cleanupErr := errors.New("cleanup failed") r.Defer(func() error { @@ -30,7 +29,7 @@ func TestError_CleanupErrorReturned(t *testing.T) { // TestError_TaskAndCleanupErrorsJoined verifies that when both a task fails // and a cleanup fails, both errors are joined and returned together. func TestError_TaskAndCleanupErrorsJoined(t *testing.T) { - r := New(logging.NewNoop()) + r := New() taskErr := errors.New("task failed") cleanupErr := errors.New("cleanup failed") @@ -52,8 +51,7 @@ func TestError_TaskAndCleanupErrorsJoined(t *testing.T) { // tasks are not reported as failures. This is expected behavior when shutdown // is triggered by context cancellation or signals. func TestError_ContextCanceledIgnored(t *testing.T) { - r := New(logging.NewNoop()) - + r := New() r.Go(func(ctx context.Context) error { <-ctx.Done() return ctx.Err() @@ -77,7 +75,7 @@ func TestError_ContextCanceledIgnored(t *testing.T) { // concurrently, the first error received triggers shutdown and is reported. // Subsequent errors from other tasks are not captured. func TestError_FirstTaskErrorWins(t *testing.T) { - r := New(logging.NewNoop()) + r := New() firstErr := errors.New("first error") secondErr := errors.New("second error") diff --git a/pkg/runner/health.go b/pkg/runner/health.go index ba6e9dac25..6b25a410dc 100644 --- a/pkg/runner/health.go +++ b/pkg/runner/health.go @@ -9,6 +9,8 @@ import ( "sync" "sync/atomic" "time" + + "github.com/unkeyed/unkey/pkg/logger" ) const ( @@ -67,7 +69,7 @@ func (r *Runner) RegisterHealth(mux *http.ServeMux, prefix ...string) { if len(prefix) > 0 { base = strings.TrimRight(prefix[0], "/") } - r.logger.Info("registering health endpoints", "base", base) + logger.Info("registering health endpoints", "base", base) mux.HandleFunc(fmt.Sprintf("GET %s/live", base), r.handleLive) mux.HandleFunc(fmt.Sprintf("GET %s/ready", base), r.handleReady) mux.HandleFunc(fmt.Sprintf("GET %s/startup", base), r.handleStartup) diff --git a/pkg/runner/health_test.go b/pkg/runner/health_test.go index 8b783ae439..4958720ddc 100644 --- a/pkg/runner/health_test.go +++ b/pkg/runner/health_test.go @@ -10,7 +10,6 @@ import ( "time" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" ) func checkHealthEndpoint(t *testing.T, mux *http.ServeMux, endpoint string, wantCode int, wantStatus string) { @@ -28,7 +27,7 @@ func checkHealthEndpoint(t *testing.T, mux *http.ServeMux, endpoint string, want } func TestHealthEndpoints_Lifecycle(t *testing.T) { - r := New(logging.NewNoop()) + r := New() mux := http.NewServeMux() r.RegisterHealth(mux, "/health") @@ -56,7 +55,7 @@ func TestHealthEndpoints_Lifecycle(t *testing.T) { } func TestHealthReady_WithChecks_AllPass(t *testing.T) { - r := New(logging.NewNoop()) + r := New() mux := http.NewServeMux() r.RegisterHealth(mux, "/health") r.health.started.Store(true) @@ -83,7 +82,7 @@ func TestHealthReady_WithChecks_AllPass(t *testing.T) { } func TestHealthReady_WithChecks_OneFails(t *testing.T) { - r := New(logging.NewNoop()) + r := New() mux := http.NewServeMux() r.RegisterHealth(mux, "/health") r.health.started.Store(true) @@ -110,7 +109,7 @@ func TestHealthReady_WithChecks_OneFails(t *testing.T) { } func TestHealthReady_CheckTimeout(t *testing.T) { - r := New(logging.NewNoop()) + r := New() mux := http.NewServeMux() r.RegisterHealth(mux, "/health") r.health.started.Store(true) @@ -138,21 +137,21 @@ func TestHealthReady_CheckTimeout(t *testing.T) { } func TestAddReadinessCheck_PanicsOnEmptyName(t *testing.T) { - r := New(logging.NewNoop()) + r := New() require.Panics(t, func() { r.AddReadinessCheck("", func(ctx context.Context) error { return nil }) }) } func TestAddReadinessCheck_PanicsOnNilCheck(t *testing.T) { - r := New(logging.NewNoop()) + r := New() require.Panics(t, func() { r.AddReadinessCheck("test", nil) }) } func TestHealthReady_ChecksRunInParallel(t *testing.T) { - r := New(logging.NewNoop()) + r := New() mux := http.NewServeMux() r.RegisterHealth(mux, "/health") r.health.started.Store(true) diff --git a/pkg/runner/run_test.go b/pkg/runner/run_test.go index e4e3db3167..64924fd0f5 100644 --- a/pkg/runner/run_test.go +++ b/pkg/runner/run_test.go @@ -9,13 +9,12 @@ import ( "time" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // TestRun_ExecutesTasks verifies that Run starts all registered tasks // concurrently when called. func TestRun_ExecutesTasks(t *testing.T) { - r := New(logging.NewNoop()) + r := New() var executed atomic.Int32 @@ -51,7 +50,7 @@ func TestRun_ExecutesTasks(t *testing.T) { // TestRun_StopsOnContextCancel verifies that canceling the parent context // signals all tasks to stop via their context. func TestRun_StopsOnContextCancel(t *testing.T) { - r := New(logging.NewNoop()) + r := New() taskStopped := make(chan struct{}) r.Go(func(ctx context.Context) error { @@ -83,7 +82,7 @@ func TestRun_StopsOnContextCancel(t *testing.T) { // TestRun_StopsOnTaskError verifies that when any task returns a non-nil // error, all other tasks are signaled to stop and the error is returned. func TestRun_StopsOnTaskError(t *testing.T) { - r := New(logging.NewNoop()) + r := New() taskErr := errors.New("task failed") r.Go(func(ctx context.Context) error { @@ -111,7 +110,7 @@ func TestRun_StopsOnTaskError(t *testing.T) { // TestRun_CanOnlyRunOnce verifies that Run returns an error if called while // already running. This prevents undefined behavior from concurrent Run calls. func TestRun_CanOnlyRunOnce(t *testing.T) { - r := New(logging.NewNoop()) + r := New() ctx, cancel := context.WithCancel(context.Background()) @@ -133,7 +132,7 @@ func TestRun_CanOnlyRunOnce(t *testing.T) { // TestRun_EmptyRunner verifies that a runner with no tasks or cleanups exits // cleanly when the context is canceled. func TestRun_EmptyRunner(t *testing.T) { - r := New(logging.NewNoop()) + r := New() ctx, cancel := context.WithCancel(context.Background()) cancel() @@ -146,7 +145,7 @@ func TestRun_EmptyRunner(t *testing.T) { // in reverse registration order (LIFO). This matches defer semantics and // ensures resources are released in the correct order. func TestRun_CleanupsExecutedInReverseOrder(t *testing.T) { - r := New(logging.NewNoop()) + r := New() var order []int var mu sync.Mutex @@ -183,7 +182,7 @@ func TestRun_CleanupsExecutedInReverseOrder(t *testing.T) { // TestRun_CleanupsReceiveContext verifies that context-aware cleanup handlers // receive a valid context with a deadline for timeout enforcement. func TestRun_CleanupsReceiveContext(t *testing.T) { - r := New(logging.NewNoop()) + r := New() var receivedCtx context.Context r.DeferCtx(func(ctx context.Context) error { @@ -203,7 +202,7 @@ func TestRun_CleanupsReceiveContext(t *testing.T) { // if one returns an error. This ensures resources are properly released even // during partial failures. func TestRun_ContinuesOnCleanupError(t *testing.T) { - r := New(logging.NewNoop()) + r := New() var called []int var mu sync.Mutex @@ -244,7 +243,7 @@ func TestRun_ContinuesOnCleanupError(t *testing.T) { // the cleanup context. Cleanup handlers that exceed this timeout will have // their context canceled. func TestWithTimeout_SetsTimeout(t *testing.T) { - r := New(logging.NewNoop()) + r := New() var cleanupCtx context.Context r.DeferCtx(func(ctx context.Context) error { diff --git a/pkg/runner/runner.go b/pkg/runner/runner.go index 64fb1a7028..47fe50d9b1 100644 --- a/pkg/runner/runner.go +++ b/pkg/runner/runner.go @@ -3,7 +3,6 @@ package runner import ( "context" "errors" - "log/slog" "os" "os/signal" "runtime/debug" @@ -11,7 +10,7 @@ import ( "syscall" "time" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) // RunFunc is a long-running goroutine that should return nil on clean exit @@ -41,7 +40,6 @@ type Runner struct { cleanups []ShutdownFunc state runnerState health *healthState - logger logging.Logger wg sync.WaitGroup errCh chan error @@ -50,7 +48,7 @@ type Runner struct { } // New creates a new Runner. -func New(logger logging.Logger) *Runner { +func New() *Runner { ctx, cancel := context.WithCancel(context.Background()) return &Runner{ @@ -58,7 +56,6 @@ func New(logger logging.Logger) *Runner { cleanups: []ShutdownFunc{}, state: runnerStateIdle, health: newHealthState(), - logger: logger.With(slog.String("component", "runner")), wg: sync.WaitGroup{}, errCh: make(chan error, 1), ctx: ctx, @@ -69,7 +66,7 @@ func New(logger logging.Logger) *Runner { // Recover logs any panic that occurs in the calling goroutine. func (r *Runner) Recover() { if recovered := recover(); recovered != nil { - r.logger.Error("panic", + logger.Error("panic", "panic", recovered, "stack", string(debug.Stack()), ) @@ -89,7 +86,7 @@ func (r *Runner) Go(fn RunFunc) { r.wg.Go(func() { err := fn(r.ctx) if err != nil && !errors.Is(err, context.Canceled) { - r.logger.Error("runner task failed", "error", err) + logger.Error("runner task failed", "error", err) select { case r.errCh <- err: default: @@ -188,7 +185,7 @@ func (r *Runner) Wait(ctx context.Context, opts ...RunOption) error { r.mu.Lock() if r.state == runnerStateRunning { r.mu.Unlock() - r.logger.Error("runner already running") + logger.Error("runner already running") return errors.New("runner is already running") } r.state = runnerStateRunning @@ -198,7 +195,7 @@ func (r *Runner) Wait(ctx context.Context, opts ...RunOption) error { } r.mu.Unlock() - r.logger.Info("runner wait started", + logger.Info("runner wait started", "timeout", cfg.Timeout, "readiness_timeout", cfg.ReadinessTimeout, ) @@ -212,19 +209,19 @@ func (r *Runner) Wait(ctx context.Context, opts ...RunOption) error { select { case sig := <-sigCh: reason = "signal" - r.logger.Info("runner shutdown signal received", "signal", sig.String()) + logger.Info("runner shutdown signal received", "signal", sig.String()) case <-ctx.Done(): reason = "context" - r.logger.Info("runner context canceled", "error", ctx.Err()) + logger.Info("runner context canceled", "error", ctx.Err()) case cause = <-r.errCh: reason = "error" } if cause != nil { - r.logger.Error("runner shutdown triggered by task error", "error", cause) + logger.Error("runner shutdown triggered by task error", "error", cause) } - r.logger.Info("runner shutting down", "reason", reason) + logger.Info("runner shutting down", "reason", reason) r.cancel() @@ -237,20 +234,20 @@ func (r *Runner) Wait(ctx context.Context, opts ...RunOption) error { if cause != nil && len(shutdownErrs) > 0 { finalErr := errors.Join(append([]error{cause}, shutdownErrs...)...) - r.logger.Error("runner shutdown failed", "error", finalErr) + logger.Error("runner shutdown failed", "error", finalErr) return finalErr } if cause != nil { - r.logger.Error("runner shutdown failed", "error", cause) + logger.Error("runner shutdown failed", "error", cause) return cause } if len(shutdownErrs) > 0 { finalErr := errors.Join(shutdownErrs...) - r.logger.Error("runner shutdown failed", "error", finalErr) + logger.Error("runner shutdown failed", "error", finalErr) return finalErr } - r.logger.Info("runner shutdown complete") + logger.Info("runner shutdown complete") return nil } @@ -272,7 +269,7 @@ func (r *Runner) shutdown(ctx context.Context) []error { continue } if err := cleanups[i](ctx); err != nil { - r.logger.Error("runner cleanup failed", "error", err) + logger.Error("runner cleanup failed", "error", err) errs = append(errs, err) } } diff --git a/pkg/runner/runner_test.go b/pkg/runner/runner_test.go index eb597c59e7..ce63243349 100644 --- a/pkg/runner/runner_test.go +++ b/pkg/runner/runner_test.go @@ -6,13 +6,12 @@ import ( "time" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // TestNew verifies that a fresh Runner starts in a clean state with no // cleanups registered and neither running nor shutting down. func TestNew(t *testing.T) { - r := New(logging.NewNoop()) + r := New() require.NotNil(t, r) require.Empty(t, r.cleanups) require.Equal(t, runnerStateIdle, r.state) @@ -22,7 +21,7 @@ func TestNew(t *testing.T) { // TestGo_StartsImmediately verifies that Go starts the task immediately. func TestGo_StartsImmediately(t *testing.T) { - r := New(logging.NewNoop()) + r := New() started := make(chan struct{}) r.Go(func(ctx context.Context) error { @@ -46,7 +45,7 @@ func TestGo_StartsImmediately(t *testing.T) { // TestDefer_RegistersCleanup verifies that Defer adds a cleanup function and // that it gets called during shutdown. func TestDefer_RegistersCleanup(t *testing.T) { - r := New(logging.NewNoop()) + r := New() called := false r.Defer(func() error { @@ -69,7 +68,7 @@ func TestDefer_RegistersCleanup(t *testing.T) { // TestDeferCtx_RegistersCleanup verifies that DeferCtx adds a context-aware // cleanup function and that it gets called during shutdown. func TestDeferCtx_RegistersCleanup(t *testing.T) { - r := New(logging.NewNoop()) + r := New() called := false r.DeferCtx(func(ctx context.Context) error { @@ -93,7 +92,7 @@ func TestDeferCtx_RegistersCleanup(t *testing.T) { // identically to DeferCtx. This alias exists for compatibility with the // otel.Registrar interface. func TestRegisterCtx_AliasForDeferCtx(t *testing.T) { - r := New(logging.NewNoop()) + r := New() called := false r.RegisterCtx(func(ctx context.Context) error { diff --git a/pkg/sim/BUILD.bazel b/pkg/sim/BUILD.bazel index 9c3fedfbe6..307bed3d13 100644 --- a/pkg/sim/BUILD.bazel +++ b/pkg/sim/BUILD.bazel @@ -12,7 +12,7 @@ go_library( visibility = ["//visibility:public"], deps = [ "//pkg/clock", - "//pkg/otel/logging", + "//pkg/logger", ], ) diff --git a/pkg/sim/simulation.go b/pkg/sim/simulation.go index 8113b09d5f..46c2c61320 100644 --- a/pkg/sim/simulation.go +++ b/pkg/sim/simulation.go @@ -7,7 +7,7 @@ import ( "time" "github.com/unkeyed/unkey/pkg/clock" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) type Validator[S any] func(*S) error @@ -27,7 +27,6 @@ type Simulation[State any] struct { applied int // Tracks how many configurations have been applied validators []Validator[State] // Add validators eventStats map[string]int // Track how many times each event is called - logger logging.Logger } // apply is a function type for configuring a simulation @@ -65,7 +64,6 @@ func New[State any](seed Seed, fns ...apply[State]) *Simulation[State] { Errors: []error{}, applied: 0, eventStats: make(map[string]int), // Initialize event stats map - logger: logging.New(), validators: []Validator[State]{}, } @@ -118,7 +116,7 @@ func (s *Simulation[State]) Run(events []Event[State]) error { } } - s.logger.Info("Simulation", + logger.Info("Simulation", "seed", s.seed.String(), "ticks", s.ticks, ) diff --git a/pkg/vault/BUILD.bazel b/pkg/vault/BUILD.bazel index cbff83877a..4242e7e011 100644 --- a/pkg/vault/BUILD.bazel +++ b/pkg/vault/BUILD.bazel @@ -18,7 +18,7 @@ go_library( "//pkg/cache/middleware", "//pkg/clock", "//pkg/encryption", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/otel/tracing", "//pkg/vault/keyring", "//pkg/vault/storage", diff --git a/pkg/vault/integration/BUILD.bazel b/pkg/vault/integration/BUILD.bazel index a4df33bbd6..acf4209cc0 100644 --- a/pkg/vault/integration/BUILD.bazel +++ b/pkg/vault/integration/BUILD.bazel @@ -11,7 +11,6 @@ go_test( ], deps = [ "//gen/proto/vault/v1:vault", - "//pkg/otel/logging", "//pkg/testutil/containers", "//pkg/uid", "//pkg/vault", diff --git a/pkg/vault/integration/coldstart_test.go b/pkg/vault/integration/coldstart_test.go index 352582d657..073fd1cb02 100644 --- a/pkg/vault/integration/coldstart_test.go +++ b/pkg/vault/integration/coldstart_test.go @@ -6,7 +6,6 @@ import ( "github.com/stretchr/testify/require" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/pkg/vault" @@ -21,14 +20,11 @@ func Test_ColdStart(t *testing.T) { s3 := containers.S3(t) - logger := logging.NewNoop() - storage, err := storage.NewS3(storage.S3Config{ S3URL: s3.HostURL, S3Bucket: "test", S3AccessKeyID: s3.AccessKeyID, S3AccessKeySecret: s3.AccessKeySecret, - Logger: logger, }) require.NoError(t, err) @@ -37,7 +33,6 @@ func Test_ColdStart(t *testing.T) { v, err := vault.New(vault.Config{ Storage: storage, - Logger: logger, MasterKeys: []string{masterKey}, }) require.NoError(t, err) diff --git a/pkg/vault/integration/migrate_deks_test.go b/pkg/vault/integration/migrate_deks_test.go index cb8955f2ca..c558976af6 100644 --- a/pkg/vault/integration/migrate_deks_test.go +++ b/pkg/vault/integration/migrate_deks_test.go @@ -10,7 +10,6 @@ import ( "github.com/stretchr/testify/require" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/pkg/vault" @@ -21,7 +20,6 @@ import ( // This scenario tests the re-encryption of a secret. func TestMigrateDeks(t *testing.T) { - logger := logging.NewNoop() data := make(map[string]string) s3 := containers.S3(t) @@ -30,7 +28,6 @@ func TestMigrateDeks(t *testing.T) { S3Bucket: fmt.Sprintf("%d", time.Now().Unix()), S3AccessKeyID: s3.AccessKeyID, S3AccessKeySecret: s3.AccessKeySecret, - Logger: logger, }) require.NoError(t, err) @@ -39,7 +36,6 @@ func TestMigrateDeks(t *testing.T) { v, err := vault.New(vault.Config{ Storage: storage, - Logger: logger, MasterKeys: []string{masterKeyOld}, }) require.NoError(t, err) @@ -72,7 +68,6 @@ func TestMigrateDeks(t *testing.T) { v, err = vault.New(vault.Config{ Storage: storage, - Logger: logger, MasterKeys: []string{masterKeyOld, masterKeyNew}, }) require.NoError(t, err) @@ -93,7 +88,6 @@ func TestMigrateDeks(t *testing.T) { v, err = vault.New(vault.Config{ Storage: storage, - Logger: logger, MasterKeys: []string{masterKeyNew}, }) require.NoError(t, err) diff --git a/pkg/vault/integration/reencryption_test.go b/pkg/vault/integration/reencryption_test.go index 606ef93a49..6df5fe2a33 100644 --- a/pkg/vault/integration/reencryption_test.go +++ b/pkg/vault/integration/reencryption_test.go @@ -9,7 +9,6 @@ import ( "github.com/stretchr/testify/require" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/pkg/vault" @@ -20,8 +19,6 @@ import ( // This scenario tests the re-encryption of a secret. func TestReEncrypt(t *testing.T) { - logger := logging.NewNoop() - s3 := containers.S3(t) storage, err := storage.NewS3(storage.S3Config{ @@ -29,7 +26,6 @@ func TestReEncrypt(t *testing.T) { S3Bucket: "vault", S3AccessKeyID: s3.AccessKeyID, S3AccessKeySecret: s3.AccessKeySecret, - Logger: logger, }) require.NoError(t, err) @@ -38,7 +34,6 @@ func TestReEncrypt(t *testing.T) { v, err := vault.New(vault.Config{ Storage: storage, - Logger: logger, MasterKeys: []string{masterKey}, }) require.NoError(t, err) diff --git a/pkg/vault/integration/reusing_deks_test.go b/pkg/vault/integration/reusing_deks_test.go index 25e431b2c0..61d4dae684 100644 --- a/pkg/vault/integration/reusing_deks_test.go +++ b/pkg/vault/integration/reusing_deks_test.go @@ -5,22 +5,20 @@ import ( "testing" "fmt" + "time" + "github.com/stretchr/testify/require" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/pkg/vault" "github.com/unkeyed/unkey/pkg/vault/keys" "github.com/unkeyed/unkey/pkg/vault/storage" - "time" ) // When encrypting multiple secrets with the same keyring, the same DEK should be reused for all of them. func TestReuseDEKsForSameKeyring(t *testing.T) { - logger := logging.NewNoop() - s3 := containers.S3(t) storage, err := storage.NewS3(storage.S3Config{ @@ -28,7 +26,6 @@ func TestReuseDEKsForSameKeyring(t *testing.T) { S3Bucket: fmt.Sprintf("%d", time.Now().UnixMilli()), S3AccessKeyID: s3.AccessKeyID, S3AccessKeySecret: s3.AccessKeySecret, - Logger: logger, }) require.NoError(t, err) @@ -37,7 +34,6 @@ func TestReuseDEKsForSameKeyring(t *testing.T) { v, err := vault.New(vault.Config{ Storage: storage, - Logger: logger, MasterKeys: []string{masterKey}, }) require.NoError(t, err) @@ -62,8 +58,6 @@ func TestReuseDEKsForSameKeyring(t *testing.T) { // When encrypting multiple secrets with different keyrings, a different DEK should be used for each keyring. func TestIndividualDEKsPerKeyring(t *testing.T) { - logger := logging.NewNoop() - s3 := containers.S3(t) storage, err := storage.NewS3(storage.S3Config{ @@ -71,7 +65,6 @@ func TestIndividualDEKsPerKeyring(t *testing.T) { S3Bucket: fmt.Sprintf("%d", time.Now().UnixMilli()), S3AccessKeyID: s3.AccessKeyID, S3AccessKeySecret: s3.AccessKeySecret, - Logger: logger, }) require.NoError(t, err) @@ -80,7 +73,6 @@ func TestIndividualDEKsPerKeyring(t *testing.T) { v, err := vault.New(vault.Config{ Storage: storage, - Logger: logger, MasterKeys: []string{masterKey}, }) require.NoError(t, err) diff --git a/pkg/vault/keyring/BUILD.bazel b/pkg/vault/keyring/BUILD.bazel index d18a8c0226..536bad9fd5 100644 --- a/pkg/vault/keyring/BUILD.bazel +++ b/pkg/vault/keyring/BUILD.bazel @@ -17,7 +17,7 @@ go_library( deps = [ "//gen/proto/vault/v1:vault", "//pkg/encryption", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/otel/tracing", "//pkg/vault/keys", "//pkg/vault/storage", diff --git a/pkg/vault/keyring/keyring.go b/pkg/vault/keyring/keyring.go index c31d7954ca..1890037ac5 100644 --- a/pkg/vault/keyring/keyring.go +++ b/pkg/vault/keyring/keyring.go @@ -4,13 +4,11 @@ import ( "fmt" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/vault/storage" ) type Keyring struct { - store storage.Storage - logger logging.Logger + store storage.Storage // any of these can be used for decryption decryptionKeys map[string]*vaultv1.KeyEncryptionKey @@ -18,8 +16,7 @@ type Keyring struct { } type Config struct { - Store storage.Storage - Logger logging.Logger + Store storage.Storage DecryptionKeys map[string]*vaultv1.KeyEncryptionKey EncryptionKey *vaultv1.KeyEncryptionKey @@ -29,7 +26,6 @@ func New(config Config) (*Keyring, error) { return &Keyring{ store: config.Store, - logger: config.Logger, encryptionKey: config.EncryptionKey, decryptionKeys: config.DecryptionKeys, }, nil diff --git a/pkg/vault/keyring/roll_keys.go b/pkg/vault/keyring/roll_keys.go index 8ff55f7e49..422255a12c 100644 --- a/pkg/vault/keyring/roll_keys.go +++ b/pkg/vault/keyring/roll_keys.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" "github.com/unkeyed/unkey/pkg/vault/storage" ) @@ -30,7 +31,7 @@ func (k *Keyring) RollKeys(ctx context.Context, ringID string) error { return fmt.Errorf("failed to decode and decrypt key: %w", err) } if encryptionKeyId == k.encryptionKey.GetId() { - k.logger.Info("key already encrypted with latest kek", + logger.Info("key already encrypted with latest kek", "keyId", dek.GetId(), ) continue diff --git a/pkg/vault/reencrypt.go b/pkg/vault/reencrypt.go index 71e3ec9712..5ef9b8dae0 100644 --- a/pkg/vault/reencrypt.go +++ b/pkg/vault/reencrypt.go @@ -5,13 +5,14 @@ import ( "fmt" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" ) func (s *Service) ReEncrypt(ctx context.Context, req *vaultv1.ReEncryptRequest) (*vaultv1.ReEncryptResponse, error) { ctx, span := tracing.Start(ctx, "vault.ReEncrypt") defer span.End() - s.logger.Info("reencrypting", + logger.Info("reencrypting", "keyring", req.GetKeyring(), ) diff --git a/pkg/vault/roll_deks.go b/pkg/vault/roll_deks.go index e712bce605..0ff180813c 100644 --- a/pkg/vault/roll_deks.go +++ b/pkg/vault/roll_deks.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" "github.com/unkeyed/unkey/pkg/vault/storage" ) @@ -29,7 +30,7 @@ func (s *Service) RollDeks(ctx context.Context) error { return fmt.Errorf("failed to decode and decrypt key: %w", err) } if kekID == s.encryptionKey.GetId() { - s.logger.Info("key already encrypted with latest kek", + logger.Info("key already encrypted with latest kek", "dekId", dek.GetId(), ) continue diff --git a/pkg/vault/service.go b/pkg/vault/service.go index 2ea3f5b47e..4eb606c214 100644 --- a/pkg/vault/service.go +++ b/pkg/vault/service.go @@ -9,7 +9,6 @@ import ( "github.com/unkeyed/unkey/pkg/cache" cacheMiddleware "github.com/unkeyed/unkey/pkg/cache/middleware" "github.com/unkeyed/unkey/pkg/clock" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/vault/keyring" "github.com/unkeyed/unkey/pkg/vault/storage" "google.golang.org/protobuf/proto" @@ -25,7 +24,6 @@ const LATEST = "LATEST" // themselves encrypted by key encryption keys (KEKs/master keys). The service // caches DEKs to reduce storage lookups and handles key rotation transparently. type Service struct { - logger logging.Logger keyCache cache.Cache[string, *vaultv1.DataEncryptionKey] storage storage.Storage @@ -38,7 +36,6 @@ type Service struct { // Config holds configuration for creating a new vault [Service]. type Config struct { - Logger logging.Logger Storage storage.Storage MasterKeys []string } @@ -56,7 +53,6 @@ func New(cfg Config) (*Service, error) { kr, err := keyring.New(keyring.Config{ Store: cfg.Storage, - Logger: cfg.Logger, DecryptionKeys: decryptionKeys, EncryptionKey: encryptionKey, }) @@ -68,7 +64,6 @@ func New(cfg Config) (*Service, error) { Fresh: time.Hour, Stale: 24 * time.Hour, MaxSize: 10000, - Logger: cfg.Logger, Resource: "data_encryption_key", Clock: clock.New(), }) @@ -77,7 +72,6 @@ func New(cfg Config) (*Service, error) { } return &Service{ - logger: cfg.Logger, storage: cfg.Storage, keyCache: cacheMiddleware.WithTracing(cache), decryptionKeys: decryptionKeys, diff --git a/pkg/vault/storage/BUILD.bazel b/pkg/vault/storage/BUILD.bazel index 11619f9913..7c7bdbcb38 100644 --- a/pkg/vault/storage/BUILD.bazel +++ b/pkg/vault/storage/BUILD.bazel @@ -11,7 +11,7 @@ go_library( visibility = ["//visibility:public"], deps = [ "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "@com_github_aws_aws_sdk_go_v2//aws", "@com_github_aws_aws_sdk_go_v2_config//:config", "@com_github_aws_aws_sdk_go_v2_credentials//:credentials", diff --git a/pkg/vault/storage/memory.go b/pkg/vault/storage/memory.go index ff54bf824a..de1abcb6b2 100644 --- a/pkg/vault/storage/memory.go +++ b/pkg/vault/storage/memory.go @@ -5,30 +5,18 @@ import ( "fmt" "strings" "sync" - - "github.com/unkeyed/unkey/pkg/otel/logging" ) // memory is an in-memory storage implementation for testing purposes. type memory struct { - config MemoryConfig - mu sync.RWMutex - data map[string][]byte - logger logging.Logger -} - -type MemoryConfig struct { - Logger logging.Logger + mu sync.RWMutex + data map[string][]byte } -func NewMemory(config MemoryConfig) (Storage, error) { - logger := config.Logger.With("service", "storage") - +func NewMemory() (Storage, error) { return &memory{ - config: config, - logger: logger, - data: make(map[string][]byte), - mu: sync.RWMutex{}, + data: make(map[string][]byte), + mu: sync.RWMutex{}, }, nil } diff --git a/pkg/vault/storage/s3.go b/pkg/vault/storage/s3.go index 0f7a9a1e19..3f2b350778 100644 --- a/pkg/vault/storage/s3.go +++ b/pkg/vault/storage/s3.go @@ -13,13 +13,12 @@ import ( awsS3 "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) type s3 struct { client *awsS3.Client config S3Config - logger logging.Logger } type S3Config struct { @@ -27,12 +26,9 @@ type S3Config struct { S3Bucket string S3AccessKeyID string S3AccessKeySecret string - Logger logging.Logger } func NewS3(config S3Config) (Storage, error) { - logger := config.Logger.With("service", "storage") - logger.Info("using s3 storage") // nolint:staticcheck @@ -66,7 +62,7 @@ func NewS3(config S3Config) (Storage, error) { logger.Info("s3 storage initialized") - return &s3{config: config, client: client, logger: logger}, nil + return &s3{config: config, client: client}, nil } func (s *s3) Key(workspaceId string, dekID string) string { diff --git a/pkg/zen/BUILD.bazel b/pkg/zen/BUILD.bazel index e8c737ed02..00baaa5594 100644 --- a/pkg/zen/BUILD.bazel +++ b/pkg/zen/BUILD.bazel @@ -16,6 +16,7 @@ go_library( "middleware_openapi_validation.go", "middleware_panic_recovery.go", "middleware_timeout.go", + "redact.go", "request_util.go", "route.go", "server.go", @@ -29,7 +30,7 @@ go_library( "//pkg/clickhouse/schema", "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/otel/tracing", "//pkg/prometheus/metrics", "//pkg/tls", @@ -49,6 +50,7 @@ go_test( "auth_test.go", "middleware_metrics_test.go", "middleware_timeout_test.go", + "redact_test.go", "route_test.go", "server_tls_test.go", "session_bind_body_test.go", @@ -62,7 +64,6 @@ go_test( "//pkg/clickhouse/schema", "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", "//pkg/tls", "//svc/api/openapi", "@com_github_stretchr_testify//assert", diff --git a/pkg/zen/README.md b/pkg/zen/README.md index 16cc8ca670..1cbd24fdfe 100644 --- a/pkg/zen/README.md +++ b/pkg/zen/README.md @@ -42,7 +42,7 @@ import ( "net/http" "github.com/unkeyed/unkey/pkg/zen" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/zen/validation" "github.com/unkeyed/unkey/pkg/fault" ) @@ -62,13 +62,10 @@ type CreateUserResponse struct { } func main() { - // Initialize logger - logger := logging.New() // Create a new server server, err := zen.New(zen.Config{ NodeID: "quickstart-server", - Logger: logger, }) if err != nil { log.Fatalf("failed to create server: %v", err) @@ -122,8 +119,8 @@ func main() { // Register routes with middleware server.RegisterRoute( []zen.Middleware{ - zen.WithLogging(logger), - zen.WithErrorHandling(logger), + zen.WithLogging(), + zen.WithErrorHandling(), }, helloRoute, ) @@ -131,8 +128,8 @@ func main() { server.RegisterRoute( []zen.Middleware{ zen.WithObservability(), - zen.WithLogging(logger), - zen.WithErrorHandling(logger), + zen.WithLogging(), + zen.WithErrorHandling(), zen.WithValidation(validator), }, createUserRoute, diff --git a/pkg/zen/doc.go b/pkg/zen/doc.go index fb12bef9c5..2d16836d50 100644 --- a/pkg/zen/doc.go +++ b/pkg/zen/doc.go @@ -23,7 +23,6 @@ // // Initialize a new server // server, err := zen.New(zen.Config{ // NodeID: "service-1", -// Logger: logger, // }) // if err != nil { // log.Fatalf("failed to create server: %v", err) @@ -43,7 +42,7 @@ // server.RegisterRoute( // []zen.Middleware{ // zen.WithTracing(), -// zen.WithLogging(logger), +// zen.WithLogging(), // zen.WithErrorHandling(), // }, // route, diff --git a/pkg/zen/middleware_errors.go b/pkg/zen/middleware_errors.go index 185c1397e6..20b56432b7 100644 --- a/pkg/zen/middleware_errors.go +++ b/pkg/zen/middleware_errors.go @@ -6,13 +6,13 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/svc/api/openapi" ) // withErrorHandling returns a lightweight error handler exclusively for testing. // only handles the specific error codes that zen package tests need to verify. -func withErrorHandling(logger logging.Logger) Middleware { +func withErrorHandling() Middleware { return func(next HandleFunc) HandleFunc { return func(ctx context.Context, s *Session) error { err := next(ctx, s) diff --git a/pkg/zen/middleware_logger.go b/pkg/zen/middleware_logger.go index e65e0c8625..5ccc2c7821 100644 --- a/pkg/zen/middleware_logger.go +++ b/pkg/zen/middleware_logger.go @@ -2,9 +2,10 @@ package zen import ( "context" - "time" + "fmt" + "log/slog" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) // WithLogging returns middleware that logs information about each request. @@ -13,29 +14,36 @@ import ( // Example: // // server.RegisterRoute( -// []zen.Middleware{zen.WithLogging(logger)}, +// []zen.Middleware{zen.WithLogging()}, // route, // ) -func WithLogging(logger logging.Logger) Middleware { +func WithLogging() Middleware { return func(next HandleFunc) HandleFunc { return func(ctx context.Context, s *Session) error { - start := time.Now() - nextErr := next(ctx, s) - serviceLatency := time.Since(start) - logger.Debug("request", - "method", s.r.Method, - "path", s.r.URL.Path, - "status", s.responseStatus, - "latency", serviceLatency.Milliseconds(), + ctx, event := logger.StartWideEvent(ctx, + fmt.Sprintf("%s %s", s.r.Method, s.r.URL.Path), ) - if nextErr != nil { - logger.Error(nextErr.Error(), - "method", s.r.Method, - "path", s.r.URL.Path, - "status", s.responseStatus) - } + defer event.End() + + nextErr := next(ctx, s) + + event.SetError(nextErr) + + event.Set( + slog.Group("http", + slog.String("method", s.r.Method), + slog.String("path", s.r.URL.Path), + slog.String("request_id", s.RequestID()), + slog.String("host", s.r.URL.Host), + slog.String("user_agent", s.r.UserAgent()), + slog.String("ip_address", s.Location()), + slog.Int("status_code", s.StatusCode()), + slog.String("request_body", string(redact(s.requestBody))), + slog.String("response_body", string(redact(s.responseBody))), + ), + ) return nextErr } } diff --git a/pkg/zen/middleware_metrics.go b/pkg/zen/middleware_metrics.go index 8e14a7069c..09a272fed9 100644 --- a/pkg/zen/middleware_metrics.go +++ b/pkg/zen/middleware_metrics.go @@ -2,7 +2,6 @@ package zen import ( "context" - "regexp" "strings" "time" @@ -13,34 +12,6 @@ type EventBuffer interface { BufferApiRequest(schema.ApiRequest) } -type redactionRule struct { - regexp *regexp.Regexp - replacement []byte -} - -var redactionRules = []redactionRule{ - // Redact "key" field values - matches JSON-style key fields with various whitespace combinations - { - regexp: regexp.MustCompile(`"key"\s*:\s*"[^"\\]*(?:\\.[^"\\]*)*"`), - replacement: []byte(`"key": "[REDACTED]"`), - }, - // Redact "plaintext" field values - matches JSON-style plaintext fields with various whitespace combinations - { - regexp: regexp.MustCompile(`"plaintext"\s*:\s*"[^"\\]*(?:\\.[^"\\]*)*"`), - replacement: []byte(`"plaintext": "[REDACTED]"`), - }, -} - -func redact(in []byte) []byte { - b := in - - for _, rule := range redactionRules { - b = rule.regexp.ReplaceAll(b, rule.replacement) - } - - return b -} - var skipHeaders = map[string]bool{ "x-forwarded-proto": true, "x-forwarded-port": true, diff --git a/pkg/zen/middleware_metrics_test.go b/pkg/zen/middleware_metrics_test.go index ec5067c003..c7b13e4947 100644 --- a/pkg/zen/middleware_metrics_test.go +++ b/pkg/zen/middleware_metrics_test.go @@ -12,7 +12,6 @@ import ( "github.com/unkeyed/unkey/pkg/clickhouse/schema" "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" ) func TestRedact(t *testing.T) { @@ -365,7 +364,6 @@ func (m *mockEventBuffer) getRequests() []schema.ApiRequest { } func TestWithMetrics_IPAddressExtraction(t *testing.T) { - logger := logging.New() tests := []struct { name string @@ -433,7 +431,7 @@ func TestWithMetrics_IPAddressExtraction(t *testing.T) { t.Run(tt.name, func(t *testing.T) { eventBuffer := &mockEventBuffer{} - server, err := New(Config{Logger: logger}) + server, err := New(Config{}) require.NoError(t, err) server.RegisterRoute( @@ -464,12 +462,11 @@ func TestWithMetrics_IPAddressExtraction(t *testing.T) { } func TestWithMetrics_HeaderFiltering(t *testing.T) { - logger := logging.New() t.Run("filters out infrastructure headers", func(t *testing.T) { eventBuffer := &mockEventBuffer{} - server, err := New(Config{Logger: logger}) + server, err := New(Config{}) require.NoError(t, err) server.RegisterRoute( @@ -526,7 +523,7 @@ func TestWithMetrics_HeaderFiltering(t *testing.T) { t.Run("redacts authorization header", func(t *testing.T) { eventBuffer := &mockEventBuffer{} - server, err := New(Config{Logger: logger}) + server, err := New(Config{}) require.NoError(t, err) server.RegisterRoute( @@ -563,12 +560,11 @@ func TestWithMetrics_HeaderFiltering(t *testing.T) { } func TestWithMetrics_InternalErrorLogging(t *testing.T) { - logger := logging.New() t.Run("logs internal error message when handler returns error", func(t *testing.T) { eventBuffer := &mockEventBuffer{} - server, err := New(Config{Logger: logger}) + server, err := New(Config{}) require.NoError(t, err) // Register a route with metrics and error handling middleware @@ -576,7 +572,7 @@ func TestWithMetrics_InternalErrorLogging(t *testing.T) { server.RegisterRoute( []Middleware{ WithMetrics(eventBuffer, InstanceInfo{Region: "test-region"}), - withErrorHandling(logger), + withErrorHandling(), }, NewRoute(http.MethodGet, "/error-test", func(ctx context.Context, s *Session) error { return fault.New("something went wrong internally", @@ -604,13 +600,13 @@ func TestWithMetrics_InternalErrorLogging(t *testing.T) { t.Run("logs chained internal error messages", func(t *testing.T) { eventBuffer := &mockEventBuffer{} - server, err := New(Config{Logger: logger}) + server, err := New(Config{}) require.NoError(t, err) server.RegisterRoute( []Middleware{ WithMetrics(eventBuffer, InstanceInfo{Region: "test-region"}), - withErrorHandling(logger), + withErrorHandling(), }, NewRoute(http.MethodGet, "/chained-error", func(ctx context.Context, s *Session) error { baseErr := fault.New("database connection failed") @@ -642,13 +638,13 @@ func TestWithMetrics_InternalErrorLogging(t *testing.T) { t.Run("no error logged when handler succeeds", func(t *testing.T) { eventBuffer := &mockEventBuffer{} - server, err := New(Config{Logger: logger}) + server, err := New(Config{}) require.NoError(t, err) server.RegisterRoute( []Middleware{ WithMetrics(eventBuffer, InstanceInfo{Region: "test-region"}), - withErrorHandling(logger), + withErrorHandling(), }, NewRoute(http.MethodGet, "/success", func(ctx context.Context, s *Session) error { return s.JSON(http.StatusOK, map[string]string{"status": "ok"}) @@ -670,13 +666,13 @@ func TestWithMetrics_InternalErrorLogging(t *testing.T) { t.Run("logs error for not found responses", func(t *testing.T) { eventBuffer := &mockEventBuffer{} - server, err := New(Config{Logger: logger}) + server, err := New(Config{}) require.NoError(t, err) server.RegisterRoute( []Middleware{ WithMetrics(eventBuffer, InstanceInfo{Region: "test-region"}), - withErrorHandling(logger), + withErrorHandling(), }, NewRoute(http.MethodGet, "/not-found-test", func(ctx context.Context, s *Session) error { return fault.New("key not found in database", diff --git a/pkg/zen/middleware_panic_recovery.go b/pkg/zen/middleware_panic_recovery.go index a3ba8a919a..5ca54ab8bd 100644 --- a/pkg/zen/middleware_panic_recovery.go +++ b/pkg/zen/middleware_panic_recovery.go @@ -8,14 +8,14 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/prometheus/metrics" "github.com/unkeyed/unkey/svc/api/openapi" ) // WithPanicRecovery returns middleware that recovers from panics and converts them // into appropriate HTTP error responses. -func WithPanicRecovery(logger logging.Logger) Middleware { +func WithPanicRecovery() Middleware { return func(next HandleFunc) HandleFunc { return func(ctx context.Context, s *Session) (err error) { defer func() { diff --git a/pkg/zen/middleware_timeout_test.go b/pkg/zen/middleware_timeout_test.go index cbdaaabf12..f0aa20471b 100644 --- a/pkg/zen/middleware_timeout_test.go +++ b/pkg/zen/middleware_timeout_test.go @@ -12,7 +12,6 @@ import ( "github.com/stretchr/testify/require" "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/svc/api/openapi" ) @@ -188,12 +187,10 @@ func TestWithTimeout(t *testing.T) { } func TestTimeoutWithErrorHandlingMiddleware(t *testing.T) { - // Create a logger for the error middleware - logger := logging.New() t.Run("server timeout returns proper HTTP 408 response", func(t *testing.T) { // Create a test server with both middlewares - server, err := New(Config{Logger: logger}) + server, err := New(Config{}) if err != nil { t.Fatalf("failed to create server: %v", err) } @@ -201,7 +198,7 @@ func TestTimeoutWithErrorHandlingMiddleware(t *testing.T) { // Register a route that times out with both middlewares server.RegisterRoute( []Middleware{ - withErrorHandling(logger), + withErrorHandling(), WithTimeout(50 * time.Millisecond), }, NewRoute(http.MethodGet, "/timeout", func(ctx context.Context, s *Session) error { @@ -237,7 +234,7 @@ func TestTimeoutWithErrorHandlingMiddleware(t *testing.T) { t.Run("client cancellation returns proper HTTP 499 response", func(t *testing.T) { // Create a test server with both middlewares - server, err := New(Config{Logger: logger}) + server, err := New(Config{}) if err != nil { t.Fatalf("failed to create server: %v", err) } @@ -245,7 +242,7 @@ func TestTimeoutWithErrorHandlingMiddleware(t *testing.T) { // Register a route that gets canceled by client server.RegisterRoute( []Middleware{ - withErrorHandling(logger), + withErrorHandling(), WithTimeout(200 * time.Millisecond), }, NewRoute(http.MethodGet, "/cancel", func(ctx context.Context, s *Session) error { @@ -290,7 +287,7 @@ func TestTimeoutWithErrorHandlingMiddleware(t *testing.T) { t.Run("successful request works normally with both middlewares", func(t *testing.T) { // Create a test server with both middlewares - server, err := New(Config{Logger: logger}) + server, err := New(Config{}) if err != nil { t.Fatalf("failed to create server: %v", err) } @@ -298,7 +295,7 @@ func TestTimeoutWithErrorHandlingMiddleware(t *testing.T) { // Register a route that completes successfully server.RegisterRoute( []Middleware{ - withErrorHandling(logger), + withErrorHandling(), WithTimeout(100 * time.Millisecond), }, NewRoute(http.MethodGet, "/success", func(ctx context.Context, s *Session) error { diff --git a/pkg/zen/redact.go b/pkg/zen/redact.go new file mode 100644 index 0000000000..e8557bcbf2 --- /dev/null +++ b/pkg/zen/redact.go @@ -0,0 +1,31 @@ +package zen + +import "regexp" + +type redactionRule struct { + regexp *regexp.Regexp + replacement []byte +} + +var redactionRules = []redactionRule{ + // Redact "key" field values - matches JSON-style key fields with various whitespace combinations + { + regexp: regexp.MustCompile(`"key"\s*:\s*"[^"\\]*(?:\\.[^"\\]*)*"`), + replacement: []byte(`"key": "[REDACTED]"`), + }, + // Redact "plaintext" field values - matches JSON-style plaintext fields with various whitespace combinations + { + regexp: regexp.MustCompile(`"plaintext"\s*:\s*"[^"\\]*(?:\\.[^"\\]*)*"`), + replacement: []byte(`"plaintext": "[REDACTED]"`), + }, +} + +func redact(in []byte) []byte { + b := in + + for _, rule := range redactionRules { + b = rule.regexp.ReplaceAll(b, rule.replacement) + } + + return b +} diff --git a/pkg/zen/redact_test.go b/pkg/zen/redact_test.go new file mode 100644 index 0000000000..07fa506361 --- /dev/null +++ b/pkg/zen/redact_test.go @@ -0,0 +1,248 @@ +package zen + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRedact_KeyField(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + in string + want string + }{ + { + name: "simple key value is redacted", + in: `{"key": "sk_live_abc123"}`, + want: `{"key": "[REDACTED]"}`, + }, + { + name: "key value with no whitespace around colon", + in: `{"key":"sk_live_abc123"}`, + want: `{"key": "[REDACTED]"}`, + }, + { + name: "key value with extra whitespace around colon", + in: `{"key" : "sk_live_abc123"}`, + want: `{"key": "[REDACTED]"}`, + }, + { + name: "key value with tab whitespace", + in: "\"key\"\t:\t\"sk_live_abc123\"", + want: `"key": "[REDACTED]"`, + }, + { + name: "key value with escaped characters", + in: `{"key": "value\"with\\escapes"}`, + want: `{"key": "[REDACTED]"}`, + }, + { + name: "key value in full key response body", + in: `{"keyId":"key_123","start":"sk_live","key":"sk_live_abcdef123456","enabled":true}`, + want: `{"keyId":"key_123","start":"sk_live","key": "[REDACTED]","enabled":true}`, + }, + { + name: "empty key value is redacted", + in: `{"key": ""}`, + want: `{"key": "[REDACTED]"}`, + }, + { + name: "key value with special characters", + in: `{"key": "sk_live_!@#$%^&*()"}`, + want: `{"key": "[REDACTED]"}`, + }, + { + name: "key value with unicode", + in: `{"key": "sk_live_\u00e9\u00e8"}`, + want: `{"key": "[REDACTED]"}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := redact([]byte(tt.in)) + require.Equal(t, tt.want, string(got)) + }) + } +} + +func TestRedact_PlaintextField(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + in string + want string + }{ + { + name: "simple plaintext value is redacted", + in: `{"plaintext": "sk_live_secret_value"}`, + want: `{"plaintext": "[REDACTED]"}`, + }, + { + name: "plaintext value with no whitespace around colon", + in: `{"plaintext":"sk_live_secret_value"}`, + want: `{"plaintext": "[REDACTED]"}`, + }, + { + name: "plaintext in key response with decrypt enabled", + in: `{"keyId":"key_123","plaintext":"sk_live_abcdef","start":"sk_live","enabled":true}`, + want: `{"keyId":"key_123","plaintext": "[REDACTED]","start":"sk_live","enabled":true}`, + }, + { + name: "plaintext value with escaped characters", + in: `{"plaintext": "value\"with\\escapes"}`, + want: `{"plaintext": "[REDACTED]"}`, + }, + { + name: "empty plaintext value is redacted", + in: `{"plaintext": ""}`, + want: `{"plaintext": "[REDACTED]"}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := redact([]byte(tt.in)) + require.Equal(t, tt.want, string(got)) + }) + } +} + +func TestRedact_BothFields(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + in string + want string + }{ + { + name: "both key and plaintext are redacted", + in: `{"key": "sk_live_abc123", "plaintext": "sk_live_abc123"}`, + want: `{"key": "[REDACTED]", "plaintext": "[REDACTED]"}`, + }, + { + name: "full create key response body", + in: `{"keyId":"key_123","key":"sk_live_newkey","name":"test","plaintext":"sk_live_newkey","enabled":true,"createdAt":1700000000}`, + want: `{"keyId":"key_123","key": "[REDACTED]","name":"test","plaintext": "[REDACTED]","enabled":true,"createdAt":1700000000}`, + }, + { + name: "nested JSON with both fields", + in: `{"data":{"key":"secret","plaintext":"also_secret"},"meta":{"requestId":"req_123"}}`, + want: `{"data":{"key": "[REDACTED]","plaintext": "[REDACTED]"},"meta":{"requestId":"req_123"}}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := redact([]byte(tt.in)) + require.Equal(t, tt.want, string(got)) + }) + } +} + +func TestRedact_NonSensitiveFieldsUnchanged(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + in string + }{ + { + name: "error response is unchanged", + in: `{"error":{"type":"https://unkey.com/docs/errors","title":"Bad Request","status":400,"detail":"Invalid request"},"meta":{"requestId":"req_123"}}`, + }, + { + name: "verify key response without sensitive fields", + in: `{"valid":true,"code":"VALID","keyId":"key_123","enabled":true}`, + }, + { + name: "ratelimit response is unchanged", + in: `{"autoApply":true,"duration":60000,"id":"rl_123","limit":100,"name":"api_requests"}`, + }, + { + name: "identity response is unchanged", + in: `{"id":"id_123","externalId":"ext_123","meta":{"plan":"pro"}}`, + }, + { + name: "empty object is unchanged", + in: `{}`, + }, + { + name: "empty input is unchanged", + in: ``, + }, + { + name: "field named apiKey is not redacted", + in: `{"apiKey": "some_value"}`, + }, + { + name: "field named keyId is not redacted", + in: `{"keyId": "key_123"}`, + }, + { + name: "plain text without quotes is unchanged", + in: `this is just plain text with key and plaintext words`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := redact([]byte(tt.in)) + require.Equal(t, tt.in, string(got)) + }) + } +} + +func TestRedact_MultipleOccurrences(t *testing.T) { + t.Parallel() + + in := `[{"key": "secret1"}, {"key": "secret2"}, {"key": "secret3"}]` + want := `[{"key": "[REDACTED]"}, {"key": "[REDACTED]"}, {"key": "[REDACTED]"}]` + + got := redact([]byte(in)) + require.Equal(t, want, string(got)) +} + +func TestRedact_PreservesNonMatchingContent(t *testing.T) { + t.Parallel() + + in := `{"keyId": "key_123", "key": "secret", "name": "my-key", "meta": {"env": "prod"}}` + got := string(redact([]byte(in))) + + require.Contains(t, got, `"keyId": "key_123"`) + require.Contains(t, got, `"key": "[REDACTED]"`) + require.Contains(t, got, `"name": "my-key"`) + require.Contains(t, got, `"meta": {"env": "prod"}`) +} + +func FuzzRedact(f *testing.F) { + f.Add([]byte(`{"key": "sk_live_abc123"}`)) + f.Add([]byte(`{"plaintext": "secret"}`)) + f.Add([]byte(`{"key": "a", "plaintext": "b"}`)) + f.Add([]byte(`{"keyId": "key_123"}`)) + f.Add([]byte(`{}`)) + f.Add([]byte(``)) + f.Add([]byte(`not json at all`)) + f.Add([]byte(`{"key": "value\"with\\escapes"}`)) + + f.Fuzz(func(t *testing.T, input []byte) { + result := redact(input) + + if len(input) > 0 { + require.NotNil(t, result) + } + + resultStr := string(result) + require.NotContains(t, resultStr, `"key": "sk_live_abc123"`) + require.NotContains(t, resultStr, `"plaintext": "secret"`) + }) +} diff --git a/pkg/zen/route_test.go b/pkg/zen/route_test.go index 044f08fc3f..c16ff42179 100644 --- a/pkg/zen/route_test.go +++ b/pkg/zen/route_test.go @@ -3,16 +3,15 @@ package zen import ( "context" "encoding/json" - "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" "net/http" "net/http/httptest" "testing" + + "github.com/stretchr/testify/require" ) func TestCatchAllRoute(t *testing.T) { - logger := logging.NewNoop() - srv, err := New(Config{Logger: logger}) + srv, err := New(Config{}) require.NoError(t, err) // Register a CATCHALL route @@ -47,8 +46,7 @@ func TestCatchAllRoute(t *testing.T) { } func TestMethodSpecificRoute(t *testing.T) { - logger := logging.NewNoop() - srv, err := New(Config{Logger: logger}) + srv, err := New(Config{}) require.NoError(t, err) // Register method-specific routes @@ -106,8 +104,7 @@ func TestMethodSpecificRoute(t *testing.T) { } func TestRoutePrecedence(t *testing.T) { - logger := logging.NewNoop() - srv, err := New(Config{Logger: logger}) + srv, err := New(Config{}) require.NoError(t, err) // Register a method-specific route first @@ -178,8 +175,7 @@ func TestNewRoute(t *testing.T) { }) t.Run("route integrates correctly with server", func(t *testing.T) { - logger := logging.NewNoop() - srv, err := New(Config{Logger: logger}) + srv, err := New(Config{}) require.NoError(t, err) called := false diff --git a/pkg/zen/server.go b/pkg/zen/server.go index 83f38c37b6..a6c5ff46ba 100644 --- a/pkg/zen/server.go +++ b/pkg/zen/server.go @@ -9,7 +9,7 @@ import ( "time" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/tls" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" @@ -24,7 +24,6 @@ import ( type Server struct { mu sync.Mutex - logger logging.Logger isListening bool mux *http.ServeMux srv *http.Server @@ -42,8 +41,6 @@ type Flags struct { // Config configures the behavior of a Server instance. type Config struct { - // Logger provides structured logging for the server. If nil, logging is disabled. - Logger logging.Logger // TLS configuration for HTTPS connections. // If this is provided, the server will use HTTPS. @@ -81,7 +78,7 @@ type Config struct { // // server, err := zen.New(zen.Config{ // InstanceID: "api-server-1", -// Logger: logger, +// , // }) // if err != nil { // log.Fatalf("failed to initialize server: %v", err) @@ -135,7 +132,6 @@ func New(config Config) (*Server, error) { } s := &Server{ mu: sync.Mutex{}, - logger: config.Logger, isListening: false, mux: mux, srv: srv, @@ -206,7 +202,7 @@ func (s *Server) Flags() Flags { func (s *Server) Serve(ctx context.Context, ln net.Listener) error { s.mu.Lock() if s.isListening { - s.logger.Warn("already listening") + logger.Warn("already listening") s.mu.Unlock() return nil } @@ -221,13 +217,13 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error { go func() { select { case <-ctx.Done(): - s.logger.Info("shutting down server due to context cancellation") + logger.Info("shutting down server due to context cancellation") shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 30*time.Second) defer shutdownCancel() err := s.Shutdown(shutdownCtx) if err != nil { - s.logger.Error("error during server shutdown", "error", err.Error()) + logger.Error("error during server shutdown", "error", err.Error()) } case <-serverCtx.Done(): // Server stopped on its own @@ -237,14 +233,14 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error { // Check if TLS should be used if s.config.TLS != nil { - s.logger.Info("listening", "srv", "https", "addr", ln.Addr().String()) + logger.Info("listening", "srv", "https", "addr", ln.Addr().String()) s.srv.TLSConfig = s.config.TLS // ListenAndServeTLS with empty strings will use the certificates from TLSConfig err = s.srv.ServeTLS(ln, "", "") } else { - s.logger.Info("listening", "srv", "http", "addr", ln.Addr().String()) + logger.Info("listening", "srv", "http", "addr", ln.Addr().String()) err = s.srv.Serve(ln) } @@ -266,19 +262,19 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error { // Example: // // server.RegisterRoute( -// []zen.Middleware{zen.WithLogging(logger), zen.WithErrorHandling()}, +// []zen.Middleware{zen.WithLogging(), zen.WithErrorHandling()}, // zen.NewRoute("GET", "/health", healthCheckHandler), // ) // // // Catch-all route that handles all methods // server.RegisterRoute( -// []zen.Middleware{zen.WithLogging(logger)}, +// []zen.Middleware{zen.WithLogging()}, // zen.NewRoute(zen.CATCHALL, "/{path...}", proxyHandler), // ) func (s *Server) RegisterRoute(middlewares []Middleware, route Route) { path := route.Path() method := route.Method() - s.logger.Info("registering", "method", method, "path", path) + logger.Info("registering", "method", method, "path", path) // Determine the pattern based on whether this is a catch-all route // Empty method means match all HTTP methods @@ -304,7 +300,7 @@ func (s *Server) RegisterRoute(middlewares []Middleware, route Route) { err := sess.Init(w, r, s.config.MaxRequestBodySize) if err != nil { - s.logger.Error("failed to init session", "error", err) + logger.Error("failed to init session", "error", err) handleFn = func(_ context.Context, _ *Session) error { return err // Return the session init error } diff --git a/pkg/zen/server_tls_test.go b/pkg/zen/server_tls_test.go index 8be1b21661..34ee275cde 100644 --- a/pkg/zen/server_tls_test.go +++ b/pkg/zen/server_tls_test.go @@ -18,7 +18,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" tlspkg "github.com/unkeyed/unkey/pkg/tls" ) @@ -80,13 +79,9 @@ func TestServerWithTLS(t *testing.T) { tlsConfig, err := tlspkg.New(certPEM, keyPEM) require.NoError(t, err, "Failed to create TLS config") - // Create a mock logger - logger := logging.New() - // Create a server with TLS config server, err := New(Config{ - Logger: logger, - TLS: tlsConfig, + TLS: tlsConfig, }) require.NoError(t, err, "Failed to create server with TLS config") @@ -175,13 +170,9 @@ func TestServerWithTLSContextCancellation(t *testing.T) { tlsConfig, err := tlspkg.New(certPEM, keyPEM) require.NoError(t, err, "Failed to create TLS config") - // Create a mock logger - logger := logging.New() - // Create a server with TLS config server, err := New(Config{ - Logger: logger, - TLS: tlsConfig, + TLS: tlsConfig, }) require.NoError(t, err, "Failed to create server with TLS config") diff --git a/pkg/zen/session_body_limit_test.go b/pkg/zen/session_body_limit_test.go index ef09b2d5e2..b01dc4cc97 100644 --- a/pkg/zen/session_body_limit_test.go +++ b/pkg/zen/session_body_limit_test.go @@ -11,7 +11,6 @@ import ( "github.com/stretchr/testify/require" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" ) func TestSession_BodySizeLimit(t *testing.T) { @@ -153,11 +152,9 @@ func TestSession_MaxBytesErrorMessage(t *testing.T) { func TestSession_BodySizeLimitHTTPStatus(t *testing.T) { // Test that oversized request bodies return 413 status through zen server - logger := logging.NewNoop() // Create server with small body size limit srv, err := New(Config{ - Logger: logger, MaxRequestBodySize: 100, // 100 byte limit }) require.NoError(t, err) @@ -174,7 +171,7 @@ func TestSession_BodySizeLimitHTTPStatus(t *testing.T) { srv.RegisterRoute( []Middleware{ - withErrorHandling(logger), + withErrorHandling(), }, testRoute, ) diff --git a/pkg/zen/session_body_read_error_test.go b/pkg/zen/session_body_read_error_test.go index abb1304019..edef3e4774 100644 --- a/pkg/zen/session_body_read_error_test.go +++ b/pkg/zen/session_body_read_error_test.go @@ -11,7 +11,6 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // failingReadCloser is a custom io.ReadCloser that always returns an error on Read @@ -47,10 +46,8 @@ func TestSession_UnreadableBodyReturns400NotError500(t *testing.T) { func TestSession_UnreadableBodyHTTPStatus(t *testing.T) { // Test that unreadable request bodies return 400 status through zen server - logger := logging.NewNoop() srv, err := New(Config{ - Logger: logger, MaxRequestBodySize: 0, // No size limit }) require.NoError(t, err) @@ -67,7 +64,7 @@ func TestSession_UnreadableBodyHTTPStatus(t *testing.T) { srv.RegisterRoute( []Middleware{ - withErrorHandling(logger), + withErrorHandling(), }, testRoute, ) diff --git a/svc/api/BUILD.bazel b/svc/api/BUILD.bazel index 8593ce1e77..88aa96c45a 100644 --- a/svc/api/BUILD.bazel +++ b/svc/api/BUILD.bazel @@ -23,8 +23,8 @@ go_library( "//pkg/counter", "//pkg/db", "//pkg/eventstream", + "//pkg/logger", "//pkg/otel", - "//pkg/otel/logging", "//pkg/prometheus", "//pkg/rbac", "//pkg/rpc/interceptor", diff --git a/svc/api/config.go b/svc/api/config.go index 3d9973ed69..c779e818e9 100644 --- a/svc/api/config.go +++ b/svc/api/config.go @@ -2,6 +2,7 @@ package api import ( "net" + "time" "github.com/unkeyed/unkey/pkg/assert" "github.com/unkeyed/unkey/pkg/clock" @@ -124,6 +125,13 @@ type Config struct { // This helps prevent DoS attacks from excessively large request bodies. MaxRequestBodySize int64 + // --- Logging sampler configuration --- + + // LogSampleRate is the baseline probability (0.0-1.0) of emitting log events. + LogSampleRate float64 + + // LogSlowThreshold defines what duration qualifies as "slow" for sampling. + LogSlowThreshold time.Duration } func (c Config) Validate() error { diff --git a/svc/api/integration/BUILD.bazel b/svc/api/integration/BUILD.bazel index c1e624e80a..99fc062079 100644 --- a/svc/api/integration/BUILD.bazel +++ b/svc/api/integration/BUILD.bazel @@ -13,7 +13,6 @@ go_library( "//pkg/clock", "//pkg/db", "//pkg/dockertest", - "//pkg/otel/logging", "//pkg/testutil/containers", "//svc/api", "//svc/api/internal/testutil/seed", diff --git a/svc/api/integration/cluster/cache/BUILD.bazel b/svc/api/integration/cluster/cache/BUILD.bazel index 52411c708f..8a86a3e985 100644 --- a/svc/api/integration/cluster/cache/BUILD.bazel +++ b/svc/api/integration/cluster/cache/BUILD.bazel @@ -12,7 +12,6 @@ go_test( "//gen/proto/cache/v1:cache", "//pkg/cache", "//pkg/eventstream", - "//pkg/otel/logging", "//pkg/testutil/containers", "//pkg/timing", "//pkg/uid", diff --git a/svc/api/integration/cluster/cache/consume_events_test.go b/svc/api/integration/cluster/cache/consume_events_test.go index 4199857c6f..f0d54ef0f0 100644 --- a/svc/api/integration/cluster/cache/consume_events_test.go +++ b/svc/api/integration/cluster/cache/consume_events_test.go @@ -11,7 +11,6 @@ import ( "github.com/stretchr/testify/require" cachev1 "github.com/unkeyed/unkey/gen/proto/cache/v1" "github.com/unkeyed/unkey/pkg/eventstream" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/pkg/timing" @@ -81,7 +80,6 @@ func TestAPI_ConsumesInvalidationEvents(t *testing.T) { Brokers: brokers, Topic: topicName, InstanceID: uid.New(uid.TestPrefix), // Use unique ID to avoid conflicts with API node - Logger: logging.NewNoop(), }) require.NoError(t, err) diff --git a/svc/api/integration/cluster/cache/e2e_test.go b/svc/api/integration/cluster/cache/e2e_test.go index 56f2c26382..eb4a4fa961 100644 --- a/svc/api/integration/cluster/cache/e2e_test.go +++ b/svc/api/integration/cluster/cache/e2e_test.go @@ -46,8 +46,9 @@ func TestDistributedCacheInvalidation_EndToEnd(t *testing.T) { require.Equal(t, api.Name, resp.Body.Data.Name, "API name should match on node %d", i) // Verify cache is populated (should show FRESH or MISS on first call) - cacheHeaders := resp.Headers.Values(timing.HeaderName) - require.NotEmpty(t, cacheHeaders, "Node %d should have cache debug headers", i) + timingHeaders := resp.Headers.Values("X-Unkey-Timing") + require.NotEmpty(t, timingHeaders, "Node %d should have cache debug headers", i) + } // Step 2: Delete API from first node (this should trigger distributed invalidation) diff --git a/svc/api/integration/cluster/cache/produce_events_test.go b/svc/api/integration/cluster/cache/produce_events_test.go index b4ecd92513..103ddc4be5 100644 --- a/svc/api/integration/cluster/cache/produce_events_test.go +++ b/svc/api/integration/cluster/cache/produce_events_test.go @@ -12,7 +12,6 @@ import ( cachev1 "github.com/unkeyed/unkey/gen/proto/cache/v1" "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/eventstream" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/svc/api/integration" @@ -33,7 +32,6 @@ func TestAPI_ProducesInvalidationEvents(t *testing.T) { Brokers: brokers, Topic: topicName, InstanceID: testInstanceID, - Logger: logging.NewNoop(), }) require.NoError(t, err) diff --git a/svc/api/integration/harness.go b/svc/api/integration/harness.go index 9ce56e4755..c27a69b8ad 100644 --- a/svc/api/integration/harness.go +++ b/svc/api/integration/harness.go @@ -13,7 +13,6 @@ import ( "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/dockertest" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/svc/api" "github.com/unkeyed/unkey/svc/api/internal/testutil/seed" @@ -64,8 +63,7 @@ func New(t *testing.T, config Config) *Harness { // Create real ClickHouse client ch, err := clickhouse.New(clickhouse.Config{ - URL: clickhouseHostDSN, - Logger: logging.NewNoop(), + URL: clickhouseHostDSN, }) require.NoError(t, err) @@ -79,7 +77,6 @@ func New(t *testing.T, config Config) *Harness { mysqlDockerCfg.DBName = "unkey" mysqlDockerDSN := mysqlDockerCfg.FormatDSN() db, err := db.New(db.Config{ - Logger: logging.NewNoop(), PrimaryDSN: mysqlHostDSN, ReadOnlyDSN: "", }) @@ -169,6 +166,8 @@ func (h *Harness) RunAPI(config ApiConfig) *ApiCluster { PprofPassword: "password", CtrlURL: "http://ctrl:7091", CtrlToken: "your-local-dev-key", + LogSampleRate: 1.0, + LogSlowThreshold: time.Second, } // Start API server in goroutine diff --git a/svc/api/internal/middleware/BUILD.bazel b/svc/api/internal/middleware/BUILD.bazel index b2e8144a6d..996b939ccc 100644 --- a/svc/api/internal/middleware/BUILD.bazel +++ b/svc/api/internal/middleware/BUILD.bazel @@ -8,7 +8,7 @@ go_library( deps = [ "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/zen", "//svc/api/openapi", ], diff --git a/svc/api/internal/middleware/errors.go b/svc/api/internal/middleware/errors.go index 94f95f1a18..90ea410bf5 100644 --- a/svc/api/internal/middleware/errors.go +++ b/svc/api/internal/middleware/errors.go @@ -6,14 +6,14 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" ) // WithErrorHandling returns middleware that translates errors into appropriate // HTTP responses based on error URNs. -func WithErrorHandling(logger logging.Logger) zen.Middleware { +func WithErrorHandling() zen.Middleware { return func(next zen.HandleFunc) zen.HandleFunc { return func(ctx context.Context, s *zen.Session) error { err := next(ctx, s) diff --git a/svc/api/internal/testutil/BUILD.bazel b/svc/api/internal/testutil/BUILD.bazel index 9b2eeb00e7..a00af6ca6f 100644 --- a/svc/api/internal/testutil/BUILD.bazel +++ b/svc/api/internal/testutil/BUILD.bazel @@ -24,7 +24,6 @@ go_library( "//pkg/counter", "//pkg/db", "//pkg/dockertest", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/testutil/containers", "//pkg/uid", diff --git a/svc/api/internal/testutil/http.go b/svc/api/internal/testutil/http.go index cb07c8f21a..863226202c 100644 --- a/svc/api/internal/testutil/http.go +++ b/svc/api/internal/testutil/http.go @@ -23,7 +23,6 @@ import ( "github.com/unkeyed/unkey/pkg/counter" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/dockertest" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/testutil/containers" "github.com/unkeyed/unkey/pkg/uid" @@ -58,7 +57,6 @@ type Harness struct { // test data that the seeder methods don't cover. DB db.Database Caches caches.Caches - Logger logging.Logger Keys keys.KeyService UsageLimiter usagelimiter.Service Auditlogs auditlogs.AuditLogService @@ -75,7 +73,6 @@ type Harness struct { // and containers are cleaned up when the test completes. func NewHarness(t *testing.T) *Harness { clk := clock.NewTestClock() - logger := logging.New() // Start all services in parallel first containers.StartAllServices(t) @@ -86,7 +83,6 @@ func NewHarness(t *testing.T) *Harness { redisUrl := dockertest.Redis(t) db, err := db.New(db.Config{ - Logger: logger, PrimaryDSN: mysqlDSN, ReadOnlyDSN: "", }) @@ -95,14 +91,12 @@ func NewHarness(t *testing.T) *Harness { caches, err := caches.New(caches.Config{ CacheInvalidationTopic: nil, NodeID: "", - Logger: logger, Clock: clk, }) require.NoError(t, err) srv, err := zen.New(zen.Config{ MaxRequestBodySize: 0, - Logger: logger, Flags: &zen.Flags{ TestMode: true, }, @@ -118,8 +112,7 @@ func NewHarness(t *testing.T) *Harness { // Create real ClickHouse client ch, err := clickhouse.New(clickhouse.Config{ - URL: chDSN, - Logger: logger, + URL: chDSN, }) require.NoError(t, err) @@ -128,19 +121,16 @@ func NewHarness(t *testing.T) *Harness { ctr, err := counter.NewRedis(counter.RedisConfig{ RedisURL: redisUrl, - Logger: logger, }) require.NoError(t, err) ratelimitService, err := ratelimit.New(ratelimit.Config{ - Logger: logger, Clock: clk, Counter: ctr, }) require.NoError(t, err) ulSvc, err := usagelimiter.NewRedisWithCounter(usagelimiter.RedisConfig{ - Logger: logger, DB: db, Counter: ctr, TTL: 60 * time.Second, @@ -148,7 +138,6 @@ func NewHarness(t *testing.T) *Harness { require.NoError(t, err) keyService, err := keys.New(keys.Config{ - Logger: logger, DB: db, KeyCache: caches.VerificationKeyByHash, RateLimiter: ratelimitService, @@ -166,14 +155,12 @@ func NewHarness(t *testing.T) *Harness { S3Bucket: "test", S3AccessKeyID: s3.AccessKeyID, S3AccessKeySecret: s3.AccessKeySecret, - Logger: logger, }) require.NoError(t, err) _, masterKey, err := masterKeys.GenerateMasterKey() require.NoError(t, err) v, err := vault.New(vault.Config{ - Logger: logger, Storage: vaultStorage, MasterKeys: []string{masterKey}, }) @@ -183,7 +170,6 @@ func NewHarness(t *testing.T) *Harness { analyticsConnManager, err := analytics.NewConnectionManager(analytics.ConnectionManagerConfig{ SettingsCache: caches.ClickhouseSetting, Database: db, - Logger: logger, Clock: clk, BaseURL: chDSN, Vault: v, @@ -196,14 +182,12 @@ func NewHarness(t *testing.T) *Harness { seeder.Seed(context.Background()) audit, err := auditlogs.New(auditlogs.Config{ - DB: db, - Logger: logger, + DB: db, }) require.NoError(t, err) h := Harness{ t: t, - Logger: logger, srv: srv, validator: validator, Keys: keyService, @@ -219,8 +203,8 @@ func NewHarness(t *testing.T) *Harness { Caches: caches, middleware: []zen.Middleware{ zen.WithObservability(), - zen.WithLogging(logger), - middleware.WithErrorHandling(logger), + zen.WithLogging(), + middleware.WithErrorHandling(), zen.WithValidation(validator), }, } diff --git a/svc/api/routes/BUILD.bazel b/svc/api/routes/BUILD.bazel index 37554be522..8bdbd7d291 100644 --- a/svc/api/routes/BUILD.bazel +++ b/svc/api/routes/BUILD.bazel @@ -18,7 +18,6 @@ go_library( "//internal/services/usagelimiter", "//pkg/clickhouse", "//pkg/db", - "//pkg/otel/logging", "//pkg/vault", "//pkg/zen", "//pkg/zen/validation", diff --git a/svc/api/routes/chproxy_metrics/BUILD.bazel b/svc/api/routes/chproxy_metrics/BUILD.bazel index 9c67ccf012..b883f021b4 100644 --- a/svc/api/routes/chproxy_metrics/BUILD.bazel +++ b/svc/api/routes/chproxy_metrics/BUILD.bazel @@ -10,7 +10,6 @@ go_library( "//pkg/clickhouse/schema", "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", "//pkg/prometheus/metrics", "//pkg/zen", ], diff --git a/svc/api/routes/chproxy_metrics/handler.go b/svc/api/routes/chproxy_metrics/handler.go index a39bb9713a..7facb795c1 100644 --- a/svc/api/routes/chproxy_metrics/handler.go +++ b/svc/api/routes/chproxy_metrics/handler.go @@ -9,7 +9,6 @@ import ( "github.com/unkeyed/unkey/pkg/clickhouse/schema" "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/prometheus/metrics" "github.com/unkeyed/unkey/pkg/zen" ) @@ -17,7 +16,6 @@ import ( // Handler handles API request metric events for ClickHouse proxy type Handler struct { ClickHouse clickhouse.ClickHouse - Logger logging.Logger Token string } diff --git a/svc/api/routes/chproxy_ratelimits/BUILD.bazel b/svc/api/routes/chproxy_ratelimits/BUILD.bazel index 751261954a..60e24eebbe 100644 --- a/svc/api/routes/chproxy_ratelimits/BUILD.bazel +++ b/svc/api/routes/chproxy_ratelimits/BUILD.bazel @@ -10,7 +10,6 @@ go_library( "//pkg/clickhouse/schema", "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", "//pkg/prometheus/metrics", "//pkg/zen", ], diff --git a/svc/api/routes/chproxy_ratelimits/handler.go b/svc/api/routes/chproxy_ratelimits/handler.go index 3b3ce66f9e..bc54aea61a 100644 --- a/svc/api/routes/chproxy_ratelimits/handler.go +++ b/svc/api/routes/chproxy_ratelimits/handler.go @@ -9,7 +9,6 @@ import ( "github.com/unkeyed/unkey/pkg/clickhouse/schema" "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/prometheus/metrics" "github.com/unkeyed/unkey/pkg/zen" ) @@ -17,7 +16,6 @@ import ( // Handler handles ratelimit events for ClickHouse proxy type Handler struct { ClickHouse clickhouse.ClickHouse - Logger logging.Logger Token string } diff --git a/svc/api/routes/chproxy_verifications/BUILD.bazel b/svc/api/routes/chproxy_verifications/BUILD.bazel index ce67c0e45b..5b69182959 100644 --- a/svc/api/routes/chproxy_verifications/BUILD.bazel +++ b/svc/api/routes/chproxy_verifications/BUILD.bazel @@ -10,7 +10,6 @@ go_library( "//pkg/clickhouse/schema", "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", "//pkg/prometheus/metrics", "//pkg/zen", ], diff --git a/svc/api/routes/chproxy_verifications/handler.go b/svc/api/routes/chproxy_verifications/handler.go index 781bd7f3c0..4b64059260 100644 --- a/svc/api/routes/chproxy_verifications/handler.go +++ b/svc/api/routes/chproxy_verifications/handler.go @@ -9,7 +9,6 @@ import ( "github.com/unkeyed/unkey/pkg/clickhouse/schema" "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/prometheus/metrics" "github.com/unkeyed/unkey/pkg/zen" ) @@ -17,7 +16,6 @@ import ( // Handler handles key verification events for ClickHouse proxy type Handler struct { ClickHouse clickhouse.ClickHouse - Logger logging.Logger Token string } diff --git a/svc/api/routes/openapi/BUILD.bazel b/svc/api/routes/openapi/BUILD.bazel index d7454c64b8..bdd7811247 100644 --- a/svc/api/routes/openapi/BUILD.bazel +++ b/svc/api/routes/openapi/BUILD.bazel @@ -6,7 +6,6 @@ go_library( importpath = "github.com/unkeyed/unkey/svc/api/routes/openapi", visibility = ["//visibility:public"], deps = [ - "//pkg/otel/logging", "//pkg/zen", "//svc/api/openapi", ], diff --git a/svc/api/routes/openapi/handler.go b/svc/api/routes/openapi/handler.go index 7dc23c1413..9e767aaf82 100644 --- a/svc/api/routes/openapi/handler.go +++ b/svc/api/routes/openapi/handler.go @@ -3,15 +3,12 @@ package handler import ( "context" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" ) // Handler implements zen.Route interface for the API reference endpoint type Handler struct { - // Services as public fields (even though not used in this handler, showing the pattern) - Logger logging.Logger } // Method returns the HTTP method this route responds to diff --git a/svc/api/routes/pprof/BUILD.bazel b/svc/api/routes/pprof/BUILD.bazel index d22f67b717..5e48f08723 100644 --- a/svc/api/routes/pprof/BUILD.bazel +++ b/svc/api/routes/pprof/BUILD.bazel @@ -8,7 +8,6 @@ go_library( deps = [ "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", "//pkg/zen", ], ) diff --git a/svc/api/routes/pprof/handler.go b/svc/api/routes/pprof/handler.go index 28607026ad..d526eb2789 100644 --- a/svc/api/routes/pprof/handler.go +++ b/svc/api/routes/pprof/handler.go @@ -7,13 +7,11 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/zen" ) // Handler handles pprof profiling endpoints type Handler struct { - Logger logging.Logger Username string Password string } diff --git a/svc/api/routes/reference/BUILD.bazel b/svc/api/routes/reference/BUILD.bazel index 40a7a41c4f..16040b398e 100644 --- a/svc/api/routes/reference/BUILD.bazel +++ b/svc/api/routes/reference/BUILD.bazel @@ -6,7 +6,6 @@ go_library( importpath = "github.com/unkeyed/unkey/svc/api/routes/reference", visibility = ["//visibility:public"], deps = [ - "//pkg/otel/logging", "//pkg/zen", "//svc/api/openapi", ], diff --git a/svc/api/routes/reference/handler.go b/svc/api/routes/reference/handler.go index a4188ad5f2..0128978e3e 100644 --- a/svc/api/routes/reference/handler.go +++ b/svc/api/routes/reference/handler.go @@ -4,15 +4,12 @@ import ( "context" "fmt" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" ) // Handler implements zen.Route interface for the API reference endpoint type Handler struct { - // Services as public fields (even though not used in this handler, showing the pattern) - Logger logging.Logger } // Method returns the HTTP method this route responds to diff --git a/svc/api/routes/register.go b/svc/api/routes/register.go index bda3e61a32..4785eaedda 100644 --- a/svc/api/routes/register.go +++ b/svc/api/routes/register.go @@ -81,9 +81,9 @@ import ( func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { withObservability := zen.WithObservability() withMetrics := zen.WithMetrics(svc.ClickHouse, info) - withLogging := zen.WithLogging(svc.Logger) - withPanicRecovery := zen.WithPanicRecovery(svc.Logger) - withErrorHandling := middleware.WithErrorHandling(svc.Logger) + withLogging := zen.WithLogging() + withPanicRecovery := zen.WithPanicRecovery() + withErrorHandling := middleware.WithErrorHandling() withValidation := zen.WithValidation(svc.Validator) withTimeout := zen.WithTimeout(time.Minute) @@ -114,21 +114,18 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { // chproxy/verifications - internal endpoint for key verification events srv.RegisterRoute(chproxyMiddlewares, &chproxyVerifications.Handler{ ClickHouse: svc.ClickHouse, - Logger: svc.Logger, Token: svc.ChproxyToken, }) // chproxy/metrics - internal endpoint for API request metrics srv.RegisterRoute(chproxyMiddlewares, &chproxyMetrics.Handler{ ClickHouse: svc.ClickHouse, - Logger: svc.Logger, Token: svc.ChproxyToken, }) // chproxy/ratelimits - internal endpoint for ratelimit events srv.RegisterRoute(chproxyMiddlewares, &chproxyRatelimits.Handler{ ClickHouse: svc.ClickHouse, - Logger: svc.Logger, Token: svc.ChproxyToken, }) } @@ -145,7 +142,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { } srv.RegisterRoute(pprofMiddlewares, &pprofRoute.Handler{ - Logger: svc.Logger, + Username: svc.PprofUsername, Password: svc.PprofPassword, }) @@ -158,7 +155,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2RatelimitLimit.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, ClickHouse: svc.ClickHouse, @@ -173,7 +170,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2RatelimitMultiLimit.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, ClickHouse: svc.ClickHouse, @@ -188,7 +185,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2RatelimitSetOverride.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -200,7 +197,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2RatelimitGetOverride.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, RatelimitNamespaceCache: svc.Caches.RatelimitNamespace, @@ -211,7 +208,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2RatelimitDeleteOverride.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -223,9 +220,9 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2RatelimitListOverrides.Handler{ - Logger: svc.Logger, - DB: svc.Database, - Keys: svc.Keys, + + DB: svc.Database, + Keys: svc.Keys, }, ) @@ -236,7 +233,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2IdentitiesCreateIdentity.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -247,7 +244,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2IdentitiesDeleteIdentity.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -258,9 +255,9 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2IdentitiesGetIdentity.Handler{ - Logger: svc.Logger, - DB: svc.Database, - Keys: svc.Keys, + + DB: svc.Database, + Keys: svc.Keys, }, ) @@ -268,9 +265,9 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2IdentitiesListIdentities.Handler{ - Logger: svc.Logger, - DB: svc.Database, - Keys: svc.Keys, + + DB: svc.Database, + Keys: svc.Keys, }, ) @@ -278,7 +275,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2IdentitiesUpdateIdentity.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -292,7 +289,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2ApisCreateApi.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -302,7 +299,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2ApisGetApi.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Caches: svc.Caches, @@ -313,7 +310,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2ApisListKeys.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Vault: svc.Vault, @@ -325,7 +322,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2ApisDeleteApi.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -340,7 +337,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2DeployCreateDeployment.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, CtrlClient: svc.CtrlDeploymentClient, @@ -351,9 +348,9 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2DeployGetDeployment.Handler{ - Logger: svc.Logger, - DB: svc.Database, - Keys: svc.Keys, + + DB: svc.Database, + Keys: svc.Keys, }, ) @@ -364,7 +361,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2PermissionsCreatePermission.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -375,9 +372,9 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2PermissionsGetPermission.Handler{ - Logger: svc.Logger, - DB: svc.Database, - Keys: svc.Keys, + + DB: svc.Database, + Keys: svc.Keys, }, ) @@ -385,9 +382,9 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2PermissionsGetRole.Handler{ - Logger: svc.Logger, - DB: svc.Database, - Keys: svc.Keys, + + DB: svc.Database, + Keys: svc.Keys, }, ) @@ -395,9 +392,9 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2PermissionsListPermissions.Handler{ - Logger: svc.Logger, - DB: svc.Database, - Keys: svc.Keys, + + DB: svc.Database, + Keys: svc.Keys, }, ) @@ -405,7 +402,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2PermissionsDeletePermission.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -416,7 +413,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2PermissionsCreateRole.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -427,9 +424,9 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2PermissionsListRoles.Handler{ - Logger: svc.Logger, - DB: svc.Database, - Keys: svc.Keys, + + DB: svc.Database, + Keys: svc.Keys, }, ) @@ -437,7 +434,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2PermissionsDeleteRole.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -451,7 +448,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysVerifyKey.Handler{ - Logger: svc.Logger, + ClickHouse: svc.ClickHouse, DB: svc.Database, Keys: svc.Keys, @@ -463,7 +460,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysMigrateKeys.Handler{ - Logger: svc.Logger, + ApiCache: svc.Caches.LiveApiByID, DB: svc.Database, Auditlogs: svc.Auditlogs, @@ -475,7 +472,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysCreateKey.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -487,7 +484,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysRerollKey.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -499,8 +496,8 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysDeleteKey.Handler{ - KeyCache: svc.Caches.VerificationKeyByHash, - Logger: svc.Logger, + KeyCache: svc.Caches.VerificationKeyByHash, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -511,7 +508,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysUpdateKey.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -524,7 +521,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysGetKey.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -536,7 +533,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysWhoami.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -548,7 +545,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysUpdateCredits.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -561,7 +558,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysSetRoles.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -573,7 +570,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysSetPermissions.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -585,7 +582,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysAddPermissions.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -597,7 +594,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysAddRoles.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -609,7 +606,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysRemovePermissions.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -621,7 +618,7 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2KeysRemoveRoles.Handler{ - Logger: svc.Logger, + DB: svc.Database, Keys: svc.Keys, Auditlogs: svc.Auditlogs, @@ -636,7 +633,6 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( defaultMiddlewares, &v2AnalyticsGetVerifications.Handler{ - Logger: svc.Logger, DB: svc.Database, Keys: svc.Keys, ClickHouse: svc.ClickHouse, @@ -658,15 +654,11 @@ func Register(srv *zen.Server, svc *Services, info zen.InstanceInfo) { srv.RegisterRoute( miscMiddlewares, - &reference.Handler{ - Logger: svc.Logger, - }, + &reference.Handler{}, ) srv.RegisterRoute( miscMiddlewares, - &openapi.Handler{ - Logger: svc.Logger, - }, + &openapi.Handler{}, ) } diff --git a/svc/api/routes/services.go b/svc/api/routes/services.go index f01bbf75e8..c18ddb8352 100644 --- a/svc/api/routes/services.go +++ b/svc/api/routes/services.go @@ -10,7 +10,6 @@ import ( "github.com/unkeyed/unkey/internal/services/usagelimiter" "github.com/unkeyed/unkey/pkg/clickhouse" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/vault" "github.com/unkeyed/unkey/pkg/zen/validation" ) @@ -23,9 +22,6 @@ import ( // All fields except the optional configuration fields (ChproxyToken, Pprof*) // must be non-nil for the API to function correctly. type Services struct { - // Logger provides structured logging for all route handlers. - Logger logging.Logger - // Database provides access to the primary MySQL database for persistence. Database db.Database diff --git a/svc/api/routes/v2_analytics_get_verifications/200_test.go b/svc/api/routes/v2_analytics_get_verifications/200_test.go index 9a9ee4295b..beb126b879 100644 --- a/svc/api/routes/v2_analytics_get_verifications/200_test.go +++ b/svc/api/routes/v2_analytics_get_verifications/200_test.go @@ -41,7 +41,6 @@ func Test200_Success(t *testing.T) { } route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -118,7 +117,6 @@ func Test200_PermissionFiltersByApiId(t *testing.T) { } route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -199,7 +197,6 @@ func Test200_PermissionFiltersByKeySpaceId(t *testing.T) { } route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -265,7 +262,6 @@ func Test200_QueryWithin30DaysRetention(t *testing.T) { }) route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -299,7 +295,6 @@ func Test200_QueryAtExact30DayRetentionLimit(t *testing.T) { rootKey := h.CreateRootKey(workspace.ID, "api.*.read_analytics") route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -331,7 +326,6 @@ func Test200_QueryWithCustomRetention90Days(t *testing.T) { rootKey := h.CreateRootKey(workspace.ID, "api.*.read_analytics") route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -409,7 +403,6 @@ func Test200_RLSWorkspaceIsolation(t *testing.T) { } route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -449,7 +442,6 @@ func Test200_QueryWithoutTimeFilter_AutoAddsFilter(t *testing.T) { rootKey := h.CreateRootKey(workspace.ID, "api.*.read_analytics") route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, diff --git a/svc/api/routes/v2_analytics_get_verifications/400_test.go b/svc/api/routes/v2_analytics_get_verifications/400_test.go index a236a63a70..ccabcc08c0 100644 --- a/svc/api/routes/v2_analytics_get_verifications/400_test.go +++ b/svc/api/routes/v2_analytics_get_verifications/400_test.go @@ -17,7 +17,6 @@ func Test400_EmptyQuery(t *testing.T) { rootKey := h.CreateRootKey(workspace.ID, "api.*.read_analytics") route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -50,7 +49,6 @@ func Test400_InvalidSQLSyntax(t *testing.T) { rootKey := h.CreateRootKey(workspace.ID, "api.*.read_analytics") route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -85,7 +83,6 @@ func Test400_UnknownColumn(t *testing.T) { rootKey := h.CreateRootKey(workspace.ID, "api.*.read_analytics") route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -118,7 +115,6 @@ func Test400_InvalidTable(t *testing.T) { rootKey := h.CreateRootKey(workspace.ID, "api.*.read_analytics") route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -151,7 +147,6 @@ func Test400_NonSelectQuery(t *testing.T) { rootKey := h.CreateRootKey(workspace.ID, "api.*.read_analytics") route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -184,7 +179,6 @@ func Test400_QueryBeyond30Days(t *testing.T) { rootKey := h.CreateRootKey(workspace.ID, "api.*.read_analytics") route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -218,7 +212,6 @@ func Test400_QueryBeyondCustomRetention90Days(t *testing.T) { rootKey := h.CreateRootKey(workspace.ID, "api.*.read_analytics") route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, diff --git a/svc/api/routes/v2_analytics_get_verifications/401_test.go b/svc/api/routes/v2_analytics_get_verifications/401_test.go index dd7397d6eb..1edc66b188 100644 --- a/svc/api/routes/v2_analytics_get_verifications/401_test.go +++ b/svc/api/routes/v2_analytics_get_verifications/401_test.go @@ -12,7 +12,6 @@ func Test401_NoAuthHeader(t *testing.T) { h := testutil.NewHarness(t) route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -37,7 +36,6 @@ func Test401_InvalidRootKey(t *testing.T) { h := testutil.NewHarness(t) route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, diff --git a/svc/api/routes/v2_analytics_get_verifications/403_test.go b/svc/api/routes/v2_analytics_get_verifications/403_test.go index aa27170cc5..993f3b5041 100644 --- a/svc/api/routes/v2_analytics_get_verifications/403_test.go +++ b/svc/api/routes/v2_analytics_get_verifications/403_test.go @@ -23,7 +23,6 @@ func Test403_NoAnalyticsPermission(t *testing.T) { rootKey := h.CreateRootKey(workspace.ID, "api.*.read_api") route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, @@ -61,7 +60,6 @@ func Test403_WrongApiPermission(t *testing.T) { rootKey := h.CreateRootKey(workspace.ID, "api."+api1.ID+".read_analytics") route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, diff --git a/svc/api/routes/v2_analytics_get_verifications/404_test.go b/svc/api/routes/v2_analytics_get_verifications/404_test.go index 7c2ef89093..4b836ad05d 100644 --- a/svc/api/routes/v2_analytics_get_verifications/404_test.go +++ b/svc/api/routes/v2_analytics_get_verifications/404_test.go @@ -21,7 +21,6 @@ func Test404_KeySpaceNotFound(t *testing.T) { rootKey := h.CreateRootKey(workspace.ID, "api.*.read_analytics") route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, diff --git a/svc/api/routes/v2_analytics_get_verifications/412_test.go b/svc/api/routes/v2_analytics_get_verifications/412_test.go index f89416fef0..098f71f4dc 100644 --- a/svc/api/routes/v2_analytics_get_verifications/412_test.go +++ b/svc/api/routes/v2_analytics_get_verifications/412_test.go @@ -22,7 +22,6 @@ func Test412_AnalyticsNotConfigured(t *testing.T) { // This will cause GetConnection to fail route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, diff --git a/svc/api/routes/v2_analytics_get_verifications/422_test.go b/svc/api/routes/v2_analytics_get_verifications/422_test.go index 3fb11b4217..536ba80369 100644 --- a/svc/api/routes/v2_analytics_get_verifications/422_test.go +++ b/svc/api/routes/v2_analytics_get_verifications/422_test.go @@ -42,7 +42,6 @@ func Test422_ExceedsMaxMemory(t *testing.T) { } route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, diff --git a/svc/api/routes/v2_analytics_get_verifications/429_test.go b/svc/api/routes/v2_analytics_get_verifications/429_test.go index 2c59ac3065..51366674f9 100644 --- a/svc/api/routes/v2_analytics_get_verifications/429_test.go +++ b/svc/api/routes/v2_analytics_get_verifications/429_test.go @@ -42,7 +42,6 @@ func Test429_QueryQuotaExceeded(t *testing.T) { } route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, diff --git a/svc/api/routes/v2_analytics_get_verifications/503_test.go b/svc/api/routes/v2_analytics_get_verifications/503_test.go index 9e5e166af6..b576f8f87d 100644 --- a/svc/api/routes/v2_analytics_get_verifications/503_test.go +++ b/svc/api/routes/v2_analytics_get_verifications/503_test.go @@ -49,7 +49,6 @@ func Test503_ClickHouseConnectionFailure(t *testing.T) { require.NoError(t, err) route := &Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, ClickHouse: h.ClickHouse, diff --git a/svc/api/routes/v2_analytics_get_verifications/BUILD.bazel b/svc/api/routes/v2_analytics_get_verifications/BUILD.bazel index 6953e0f7b8..5124413fb8 100644 --- a/svc/api/routes/v2_analytics_get_verifications/BUILD.bazel +++ b/svc/api/routes/v2_analytics_get_verifications/BUILD.bazel @@ -16,7 +16,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_analytics_get_verifications/handler.go b/svc/api/routes/v2_analytics_get_verifications/handler.go index 8809c6e63f..48862c36ea 100644 --- a/svc/api/routes/v2_analytics_get_verifications/handler.go +++ b/svc/api/routes/v2_analytics_get_verifications/handler.go @@ -17,7 +17,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -47,7 +47,6 @@ var ( // Handler implements zen.Route interface for the v2 Analytics get verifications endpoint type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService ClickHouse clickhouse.ClickHouse @@ -97,7 +96,6 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { TableAliases: tableAliases, AllowedTables: allowedTables, MaxQueryRangeDays: settings.Quotas.LogsRetentionDays, - Logger: h.Logger, }) parsedQuery, err := parser.Parse(ctx, req.Query) @@ -131,7 +129,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { return err } - h.Logger.Debug("executing query", "original", req.Query, "parsed", parsedQuery) + logger.Debug("executing query", "original", req.Query, "parsed", parsedQuery) // Execute query using workspace connection verifications, err := conn.QueryToMaps(ctx, parsedQuery) diff --git a/svc/api/routes/v2_apis_create_api/200_test.go b/svc/api/routes/v2_apis_create_api/200_test.go index 2f17201b95..6da6fb0603 100644 --- a/svc/api/routes/v2_apis_create_api/200_test.go +++ b/svc/api/routes/v2_apis_create_api/200_test.go @@ -23,7 +23,6 @@ func TestCreateApiSuccessfully(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_apis_create_api/400_test.go b/svc/api/routes/v2_apis_create_api/400_test.go index 24f7e7608a..8700e22f62 100644 --- a/svc/api/routes/v2_apis_create_api/400_test.go +++ b/svc/api/routes/v2_apis_create_api/400_test.go @@ -22,7 +22,6 @@ func TestCreateApi_BadRequest(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_apis_create_api/401_test.go b/svc/api/routes/v2_apis_create_api/401_test.go index b9c286e70e..bda235fc18 100644 --- a/svc/api/routes/v2_apis_create_api/401_test.go +++ b/svc/api/routes/v2_apis_create_api/401_test.go @@ -17,7 +17,6 @@ func TestCreateApi_Unauthorized(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_apis_create_api/403_test.go b/svc/api/routes/v2_apis_create_api/403_test.go index 3751496702..03b2f2fcb1 100644 --- a/svc/api/routes/v2_apis_create_api/403_test.go +++ b/svc/api/routes/v2_apis_create_api/403_test.go @@ -20,7 +20,6 @@ func TestCreateApi_Forbidden(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_apis_create_api/BUILD.bazel b/svc/api/routes/v2_apis_create_api/BUILD.bazel index e09b6f4b7b..6cc674324d 100644 --- a/svc/api/routes/v2_apis_create_api/BUILD.bazel +++ b/svc/api/routes/v2_apis_create_api/BUILD.bazel @@ -12,7 +12,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/uid", "//pkg/zen", diff --git a/svc/api/routes/v2_apis_create_api/handler.go b/svc/api/routes/v2_apis_create_api/handler.go index b7be81472e..79aa0662c2 100644 --- a/svc/api/routes/v2_apis_create_api/handler.go +++ b/svc/api/routes/v2_apis_create_api/handler.go @@ -13,7 +13,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/pkg/zen" @@ -24,7 +23,6 @@ type Request = openapi.V2ApisCreateApiRequestBody type Response = openapi.V2ApisCreateApiResponseBody type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService diff --git a/svc/api/routes/v2_apis_delete_api/200_test.go b/svc/api/routes/v2_apis_delete_api/200_test.go index 366d9c2484..8cfc761626 100644 --- a/svc/api/routes/v2_apis_delete_api/200_test.go +++ b/svc/api/routes/v2_apis_delete_api/200_test.go @@ -18,7 +18,6 @@ func TestSuccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_apis_delete_api/400_test.go b/svc/api/routes/v2_apis_delete_api/400_test.go index d566d7f1ef..88c2c5485c 100644 --- a/svc/api/routes/v2_apis_delete_api/400_test.go +++ b/svc/api/routes/v2_apis_delete_api/400_test.go @@ -15,7 +15,6 @@ func TestValidationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_apis_delete_api/401_test.go b/svc/api/routes/v2_apis_delete_api/401_test.go index 620e455f80..96f93129cf 100644 --- a/svc/api/routes/v2_apis_delete_api/401_test.go +++ b/svc/api/routes/v2_apis_delete_api/401_test.go @@ -14,7 +14,6 @@ func TestAuthenticationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_apis_delete_api/403_test.go b/svc/api/routes/v2_apis_delete_api/403_test.go index 6193d42971..3951861bf1 100644 --- a/svc/api/routes/v2_apis_delete_api/403_test.go +++ b/svc/api/routes/v2_apis_delete_api/403_test.go @@ -17,7 +17,6 @@ func TestAuthorizationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_apis_delete_api/404_test.go b/svc/api/routes/v2_apis_delete_api/404_test.go index b8b735a35e..04aed11f6d 100644 --- a/svc/api/routes/v2_apis_delete_api/404_test.go +++ b/svc/api/routes/v2_apis_delete_api/404_test.go @@ -20,7 +20,6 @@ func TestNotFoundErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_apis_delete_api/412_test.go b/svc/api/routes/v2_apis_delete_api/412_test.go index b70cfc3fa1..46d9a77c72 100644 --- a/svc/api/routes/v2_apis_delete_api/412_test.go +++ b/svc/api/routes/v2_apis_delete_api/412_test.go @@ -20,7 +20,6 @@ func TestDeleteProtection(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_apis_delete_api/BUILD.bazel b/svc/api/routes/v2_apis_delete_api/BUILD.bazel index 8bad08af8f..e93d5fe6f2 100644 --- a/svc/api/routes/v2_apis_delete_api/BUILD.bazel +++ b/svc/api/routes/v2_apis_delete_api/BUILD.bazel @@ -14,7 +14,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_apis_delete_api/cache_validation_test.go b/svc/api/routes/v2_apis_delete_api/cache_validation_test.go index 4f5eefa128..723c408438 100644 --- a/svc/api/routes/v2_apis_delete_api/cache_validation_test.go +++ b/svc/api/routes/v2_apis_delete_api/cache_validation_test.go @@ -20,7 +20,6 @@ func TestCacheInvalidation(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_apis_delete_api/handler.go b/svc/api/routes/v2_apis_delete_api/handler.go index 7e63556319..1873869495 100644 --- a/svc/api/routes/v2_apis_delete_api/handler.go +++ b/svc/api/routes/v2_apis_delete_api/handler.go @@ -15,7 +15,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -28,8 +27,6 @@ type ( // Handler implements zen.Route interface for the v2 APIs delete API endpoint type Handler struct { - // Services as public fields - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService diff --git a/svc/api/routes/v2_apis_delete_api/idempotent_test.go b/svc/api/routes/v2_apis_delete_api/idempotent_test.go index ab46fe77af..76a09344c5 100644 --- a/svc/api/routes/v2_apis_delete_api/idempotent_test.go +++ b/svc/api/routes/v2_apis_delete_api/idempotent_test.go @@ -16,7 +16,6 @@ func TestIdempotentDeletion(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_apis_get_api/200_test.go b/svc/api/routes/v2_apis_get_api/200_test.go index c2356583a8..a42edd2772 100644 --- a/svc/api/routes/v2_apis_get_api/200_test.go +++ b/svc/api/routes/v2_apis_get_api/200_test.go @@ -21,7 +21,6 @@ func TestGetApiSuccessfully(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Caches: h.Caches, diff --git a/svc/api/routes/v2_apis_get_api/400_test.go b/svc/api/routes/v2_apis_get_api/400_test.go index 81db956048..4a29ff7ab5 100644 --- a/svc/api/routes/v2_apis_get_api/400_test.go +++ b/svc/api/routes/v2_apis_get_api/400_test.go @@ -14,7 +14,6 @@ func TestGetApiInvalidRequest(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Caches: h.Caches, diff --git a/svc/api/routes/v2_apis_get_api/403_test.go b/svc/api/routes/v2_apis_get_api/403_test.go index 2165910ad7..ef8b29fa88 100644 --- a/svc/api/routes/v2_apis_get_api/403_test.go +++ b/svc/api/routes/v2_apis_get_api/403_test.go @@ -17,7 +17,6 @@ func TestGetApiInsufficientPermissions(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Caches: h.Caches, diff --git a/svc/api/routes/v2_apis_get_api/404_test.go b/svc/api/routes/v2_apis_get_api/404_test.go index 15e1cc355f..e86eb9db36 100644 --- a/svc/api/routes/v2_apis_get_api/404_test.go +++ b/svc/api/routes/v2_apis_get_api/404_test.go @@ -22,7 +22,6 @@ func TestGetApiNotFound(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Caches: h.Caches, diff --git a/svc/api/routes/v2_apis_get_api/BUILD.bazel b/svc/api/routes/v2_apis_get_api/BUILD.bazel index 9e1cce8270..fbc9256d53 100644 --- a/svc/api/routes/v2_apis_get_api/BUILD.bazel +++ b/svc/api/routes/v2_apis_get_api/BUILD.bazel @@ -12,7 +12,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_apis_get_api/handler.go b/svc/api/routes/v2_apis_get_api/handler.go index 3d6765b733..2326208634 100644 --- a/svc/api/routes/v2_apis_get_api/handler.go +++ b/svc/api/routes/v2_apis_get_api/handler.go @@ -10,7 +10,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -21,8 +20,6 @@ type Response = openapi.V2ApisGetApiResponseBody // Handler implements zen.Route interface for the v2 APIs get API endpoint type Handler struct { - // Services as public fields - Logger logging.Logger DB db.Database Keys keys.KeyService Caches caches.Caches @@ -40,7 +37,6 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/apis.getApi") auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() if err != nil { diff --git a/svc/api/routes/v2_apis_list_keys/200_test.go b/svc/api/routes/v2_apis_list_keys/200_test.go index 576e6266f8..80ebaf477a 100644 --- a/svc/api/routes/v2_apis_list_keys/200_test.go +++ b/svc/api/routes/v2_apis_list_keys/200_test.go @@ -23,7 +23,6 @@ func TestSuccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Vault: h.Vault, diff --git a/svc/api/routes/v2_apis_list_keys/400_test.go b/svc/api/routes/v2_apis_list_keys/400_test.go index 745dc96c63..f3a0b8f404 100644 --- a/svc/api/routes/v2_apis_list_keys/400_test.go +++ b/svc/api/routes/v2_apis_list_keys/400_test.go @@ -15,7 +15,6 @@ func TestValidationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Vault: h.Vault, diff --git a/svc/api/routes/v2_apis_list_keys/401_test.go b/svc/api/routes/v2_apis_list_keys/401_test.go index 4752e2d2f5..beed720baf 100644 --- a/svc/api/routes/v2_apis_list_keys/401_test.go +++ b/svc/api/routes/v2_apis_list_keys/401_test.go @@ -14,7 +14,6 @@ func TestAuthenticationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Vault: h.Vault, diff --git a/svc/api/routes/v2_apis_list_keys/403_test.go b/svc/api/routes/v2_apis_list_keys/403_test.go index aadfe6e5c2..26ebb734c8 100644 --- a/svc/api/routes/v2_apis_list_keys/403_test.go +++ b/svc/api/routes/v2_apis_list_keys/403_test.go @@ -21,7 +21,6 @@ func TestAuthorizationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Vault: h.Vault, diff --git a/svc/api/routes/v2_apis_list_keys/404_test.go b/svc/api/routes/v2_apis_list_keys/404_test.go index 8ecafe256b..f1cb6907d3 100644 --- a/svc/api/routes/v2_apis_list_keys/404_test.go +++ b/svc/api/routes/v2_apis_list_keys/404_test.go @@ -22,7 +22,6 @@ func TestNotFoundErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Vault: h.Vault, diff --git a/svc/api/routes/v2_apis_list_keys/412_test.go b/svc/api/routes/v2_apis_list_keys/412_test.go index 012a43f6b1..40bd384708 100644 --- a/svc/api/routes/v2_apis_list_keys/412_test.go +++ b/svc/api/routes/v2_apis_list_keys/412_test.go @@ -22,7 +22,6 @@ func TestPreconditionError(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Vault: h.Vault, diff --git a/svc/api/routes/v2_apis_list_keys/BUILD.bazel b/svc/api/routes/v2_apis_list_keys/BUILD.bazel index 9bb814fc84..e06af00db7 100644 --- a/svc/api/routes/v2_apis_list_keys/BUILD.bazel +++ b/svc/api/routes/v2_apis_list_keys/BUILD.bazel @@ -13,7 +13,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/ptr", "//pkg/rbac", "//pkg/vault", diff --git a/svc/api/routes/v2_apis_list_keys/handler.go b/svc/api/routes/v2_apis_list_keys/handler.go index 24eff501bc..afac577e30 100644 --- a/svc/api/routes/v2_apis_list_keys/handler.go +++ b/svc/api/routes/v2_apis_list_keys/handler.go @@ -13,7 +13,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/vault" @@ -28,7 +28,6 @@ type ( // Handler implements zen.Route interface for the v2 APIs list keys endpoint type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Vault *vault.Service @@ -243,7 +242,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { Encrypted: key.EncryptedKey.String, }) if decryptErr != nil { - h.Logger.Error("failed to decrypt key", + logger.Error("failed to decrypt key", "keyId", key.ID, "error", decryptErr, ) @@ -332,7 +331,7 @@ func (h *Handler) buildKeyResponseData(keyData *db.KeyData, plaintext string) op identityMeta, err := db.UnmarshalNullableJSONTo[map[string]any](keyData.Identity.Meta) response.Identity.Meta = identityMeta if err != nil { - h.Logger.Error("failed to unmarshal identity meta", "error", err) + logger.Error("failed to unmarshal identity meta", "error", err) } } @@ -397,7 +396,7 @@ func (h *Handler) buildKeyResponseData(keyData *db.KeyData, plaintext string) op // Set meta meta, err := db.UnmarshalNullableJSONTo[map[string]any](keyData.Key.Meta.String) if err != nil { - h.Logger.Error("failed to unmarshal key meta", + logger.Error("failed to unmarshal key meta", "keyId", keyData.Key.ID, "error", err, ) diff --git a/svc/api/routes/v2_deploy_create_deployment/200_test.go b/svc/api/routes/v2_deploy_create_deployment/200_test.go index c111424d6d..a1120aec06 100644 --- a/svc/api/routes/v2_deploy_create_deployment/200_test.go +++ b/svc/api/routes/v2_deploy_create_deployment/200_test.go @@ -19,9 +19,8 @@ func TestCreateDeploymentSuccessfully(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, CtrlClient: &testutil.MockDeploymentClient{ CreateDeploymentFunc: func(ctx context.Context, req *connect.Request[ctrlv1.CreateDeploymentRequest]) (*connect.Response[ctrlv1.CreateDeploymentResponse], error) { return connect.NewResponse(&ctrlv1.CreateDeploymentResponse{DeploymentId: "test-deployment-id"}), nil @@ -102,9 +101,8 @@ func TestCreateDeploymentWithWildcardPermission(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, CtrlClient: &testutil.MockDeploymentClient{ CreateDeploymentFunc: func(ctx context.Context, req *connect.Request[ctrlv1.CreateDeploymentRequest]) (*connect.Response[ctrlv1.CreateDeploymentResponse], error) { return connect.NewResponse(&ctrlv1.CreateDeploymentResponse{DeploymentId: "test-deployment-id"}), nil @@ -139,9 +137,8 @@ func TestCreateDeploymentWithSpecificProjectPermission(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, CtrlClient: &testutil.MockDeploymentClient{ CreateDeploymentFunc: func(ctx context.Context, req *connect.Request[ctrlv1.CreateDeploymentRequest]) (*connect.Response[ctrlv1.CreateDeploymentResponse], error) { return connect.NewResponse(&ctrlv1.CreateDeploymentResponse{DeploymentId: "test-deployment-id"}), nil diff --git a/svc/api/routes/v2_deploy_create_deployment/400_test.go b/svc/api/routes/v2_deploy_create_deployment/400_test.go index fcd54a13d5..258e82d7e6 100644 --- a/svc/api/routes/v2_deploy_create_deployment/400_test.go +++ b/svc/api/routes/v2_deploy_create_deployment/400_test.go @@ -18,9 +18,8 @@ func TestBadRequests(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, CtrlClient: &testutil.MockDeploymentClient{ CreateDeploymentFunc: func(ctx context.Context, req *connect.Request[ctrlv1.CreateDeploymentRequest]) (*connect.Response[ctrlv1.CreateDeploymentResponse], error) { return connect.NewResponse(&ctrlv1.CreateDeploymentResponse{DeploymentId: "test-deployment-id"}), nil diff --git a/svc/api/routes/v2_deploy_create_deployment/401_test.go b/svc/api/routes/v2_deploy_create_deployment/401_test.go index 3029eb4809..f7f5456cbe 100644 --- a/svc/api/routes/v2_deploy_create_deployment/401_test.go +++ b/svc/api/routes/v2_deploy_create_deployment/401_test.go @@ -16,9 +16,8 @@ func TestUnauthorizedAccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, CtrlClient: &testutil.MockDeploymentClient{ CreateDeploymentFunc: func(ctx context.Context, req *connect.Request[ctrlv1.CreateDeploymentRequest]) (*connect.Response[ctrlv1.CreateDeploymentResponse], error) { return connect.NewResponse(&ctrlv1.CreateDeploymentResponse{DeploymentId: "test-deployment-id"}), nil diff --git a/svc/api/routes/v2_deploy_create_deployment/403_test.go b/svc/api/routes/v2_deploy_create_deployment/403_test.go index 201505304f..c9b6fa3d32 100644 --- a/svc/api/routes/v2_deploy_create_deployment/403_test.go +++ b/svc/api/routes/v2_deploy_create_deployment/403_test.go @@ -19,9 +19,8 @@ func TestCreateDeploymentInsufficientPermissions(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, CtrlClient: &testutil.MockDeploymentClient{ CreateDeploymentFunc: func(ctx context.Context, req *connect.Request[ctrlv1.CreateDeploymentRequest]) (*connect.Response[ctrlv1.CreateDeploymentResponse], error) { return connect.NewResponse(&ctrlv1.CreateDeploymentResponse{DeploymentId: "test-deployment-id"}), nil diff --git a/svc/api/routes/v2_deploy_create_deployment/404_test.go b/svc/api/routes/v2_deploy_create_deployment/404_test.go index 9f608c22b7..9df4a45a9b 100644 --- a/svc/api/routes/v2_deploy_create_deployment/404_test.go +++ b/svc/api/routes/v2_deploy_create_deployment/404_test.go @@ -23,9 +23,8 @@ func TestProjectNotFound(t *testing.T) { }) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, CtrlClient: &testutil.MockDeploymentClient{ CreateDeploymentFunc: func(ctx context.Context, req *connect.Request[ctrlv1.CreateDeploymentRequest]) (*connect.Response[ctrlv1.CreateDeploymentResponse], error) { return connect.NewResponse(&ctrlv1.CreateDeploymentResponse{DeploymentId: "test-deployment-id"}), nil @@ -62,9 +61,8 @@ func TestEnvironmentNotFound(t *testing.T) { }) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, CtrlClient: &testutil.MockDeploymentClient{ CreateDeploymentFunc: func(ctx context.Context, req *connect.Request[ctrlv1.CreateDeploymentRequest]) (*connect.Response[ctrlv1.CreateDeploymentResponse], error) { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("environment not found")) diff --git a/svc/api/routes/v2_deploy_create_deployment/BUILD.bazel b/svc/api/routes/v2_deploy_create_deployment/BUILD.bazel index 34caca2429..98f7c15263 100644 --- a/svc/api/routes/v2_deploy_create_deployment/BUILD.bazel +++ b/svc/api/routes/v2_deploy_create_deployment/BUILD.bazel @@ -12,7 +12,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/zen", "//svc/api/internal/ctrlclient", diff --git a/svc/api/routes/v2_deploy_create_deployment/handler.go b/svc/api/routes/v2_deploy_create_deployment/handler.go index e316e9a126..919acb73fe 100644 --- a/svc/api/routes/v2_deploy_create_deployment/handler.go +++ b/svc/api/routes/v2_deploy_create_deployment/handler.go @@ -11,7 +11,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/internal/ctrlclient" @@ -24,7 +23,6 @@ type ( ) type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService CtrlClient ctrlv1connect.DeploymentServiceClient diff --git a/svc/api/routes/v2_deploy_get_deployment/200_test.go b/svc/api/routes/v2_deploy_get_deployment/200_test.go index e347c70caf..e6e76d8af6 100644 --- a/svc/api/routes/v2_deploy_get_deployment/200_test.go +++ b/svc/api/routes/v2_deploy_get_deployment/200_test.go @@ -30,9 +30,8 @@ func TestGetDeploymentSuccessfully(t *testing.T) { }) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } h.Register(route) @@ -78,9 +77,8 @@ func TestGetDeploymentWithWildcardPermission(t *testing.T) { }) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } h.Register(route) @@ -118,9 +116,8 @@ func TestGetDeploymentWithSpecificProjectPermission(t *testing.T) { }) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_deploy_get_deployment/400_test.go b/svc/api/routes/v2_deploy_get_deployment/400_test.go index a561136085..75e9ccd83b 100644 --- a/svc/api/routes/v2_deploy_get_deployment/400_test.go +++ b/svc/api/routes/v2_deploy_get_deployment/400_test.go @@ -15,9 +15,8 @@ func TestBadRequests(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_deploy_get_deployment/401_test.go b/svc/api/routes/v2_deploy_get_deployment/401_test.go index 6b990f27ec..df905753a2 100644 --- a/svc/api/routes/v2_deploy_get_deployment/401_test.go +++ b/svc/api/routes/v2_deploy_get_deployment/401_test.go @@ -13,9 +13,8 @@ func TestUnauthorizedAccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_deploy_get_deployment/403_test.go b/svc/api/routes/v2_deploy_get_deployment/403_test.go index 435d0db38b..ed444864ab 100644 --- a/svc/api/routes/v2_deploy_get_deployment/403_test.go +++ b/svc/api/routes/v2_deploy_get_deployment/403_test.go @@ -32,9 +32,8 @@ func TestGetDeploymentInsufficientPermissions(t *testing.T) { }) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_deploy_get_deployment/404_test.go b/svc/api/routes/v2_deploy_get_deployment/404_test.go index 5ece49dd4f..8d4cdb848a 100644 --- a/svc/api/routes/v2_deploy_get_deployment/404_test.go +++ b/svc/api/routes/v2_deploy_get_deployment/404_test.go @@ -14,9 +14,8 @@ func TestNotFound(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_deploy_get_deployment/BUILD.bazel b/svc/api/routes/v2_deploy_get_deployment/BUILD.bazel index e30af0d7e5..6d7c76fb47 100644 --- a/svc/api/routes/v2_deploy_get_deployment/BUILD.bazel +++ b/svc/api/routes/v2_deploy_get_deployment/BUILD.bazel @@ -10,7 +10,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_deploy_get_deployment/handler.go b/svc/api/routes/v2_deploy_get_deployment/handler.go index c0ab2773f2..14331e2e3a 100644 --- a/svc/api/routes/v2_deploy_get_deployment/handler.go +++ b/svc/api/routes/v2_deploy_get_deployment/handler.go @@ -8,7 +8,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -20,9 +20,8 @@ type ( ) type Handler struct { - Logger logging.Logger - DB db.Database - Keys keys.KeyService + DB db.Database + Keys keys.KeyService } func (h *Handler) Path() string { @@ -97,7 +96,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { // Fetch hostnames from frontline routes routes, routesErr := db.Query.FindFrontlineRoutesByDeploymentID(ctx, h.DB.RO(), req.DeploymentId) if routesErr != nil { - h.Logger.Warn("failed to fetch frontline routes for deployment", "error", routesErr, "deployment_id", deployment.ID) + logger.Warn("failed to fetch frontline routes for deployment", "error", routesErr, "deployment_id", deployment.ID) } else if len(routes) > 0 { hostnames := make([]string, len(routes)) for i, route := range routes { diff --git a/svc/api/routes/v2_identities_create_identity/200_test.go b/svc/api/routes/v2_identities_create_identity/200_test.go index 30fd583f4d..e29517237c 100644 --- a/svc/api/routes/v2_identities_create_identity/200_test.go +++ b/svc/api/routes/v2_identities_create_identity/200_test.go @@ -21,7 +21,6 @@ func TestCreateIdentitySuccessfully(t *testing.T) { ctx := context.Background() h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_create_identity/400_test.go b/svc/api/routes/v2_identities_create_identity/400_test.go index b2bf3d3b6a..aea6025c41 100644 --- a/svc/api/routes/v2_identities_create_identity/400_test.go +++ b/svc/api/routes/v2_identities_create_identity/400_test.go @@ -19,7 +19,6 @@ func TestBadRequests(t *testing.T) { rootKey := h.CreateRootKey(h.Resources().UserWorkspace.ID, "identity.*.create_identity") route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_create_identity/401_test.go b/svc/api/routes/v2_identities_create_identity/401_test.go index 2eda0dc80f..38d6ef4289 100644 --- a/svc/api/routes/v2_identities_create_identity/401_test.go +++ b/svc/api/routes/v2_identities_create_identity/401_test.go @@ -15,7 +15,6 @@ func TestUnauthorizedAccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_create_identity/403_test.go b/svc/api/routes/v2_identities_create_identity/403_test.go index 769738db78..c0ee9a8c10 100644 --- a/svc/api/routes/v2_identities_create_identity/403_test.go +++ b/svc/api/routes/v2_identities_create_identity/403_test.go @@ -15,7 +15,6 @@ func TestWorkspacePermissions(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_create_identity/409_test.go b/svc/api/routes/v2_identities_create_identity/409_test.go index d4dd9b6011..f1821186e5 100644 --- a/svc/api/routes/v2_identities_create_identity/409_test.go +++ b/svc/api/routes/v2_identities_create_identity/409_test.go @@ -16,7 +16,6 @@ func TestCreateIdentityDuplicate(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_create_identity/BUILD.bazel b/svc/api/routes/v2_identities_create_identity/BUILD.bazel index adeef80f4f..96fd77737a 100644 --- a/svc/api/routes/v2_identities_create_identity/BUILD.bazel +++ b/svc/api/routes/v2_identities_create_identity/BUILD.bazel @@ -12,7 +12,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/uid", "//pkg/zen", diff --git a/svc/api/routes/v2_identities_create_identity/handler.go b/svc/api/routes/v2_identities_create_identity/handler.go index 8bc801a8c4..63cd473d7e 100644 --- a/svc/api/routes/v2_identities_create_identity/handler.go +++ b/svc/api/routes/v2_identities_create_identity/handler.go @@ -14,7 +14,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/pkg/zen" @@ -26,8 +25,6 @@ type Response = openapi.V2IdentitiesCreateIdentityResponseBody // Handler implements zen.Route interface for the v2 identities create identity endpoint type Handler struct { - // Services as public fields - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService diff --git a/svc/api/routes/v2_identities_delete_identity/200_test.go b/svc/api/routes/v2_identities_delete_identity/200_test.go index 51967a31db..8468f9da87 100644 --- a/svc/api/routes/v2_identities_delete_identity/200_test.go +++ b/svc/api/routes/v2_identities_delete_identity/200_test.go @@ -22,7 +22,6 @@ func TestDeleteIdentitySuccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_delete_identity/400_test.go b/svc/api/routes/v2_identities_delete_identity/400_test.go index d70c6b93ea..9e99f7e5c2 100644 --- a/svc/api/routes/v2_identities_delete_identity/400_test.go +++ b/svc/api/routes/v2_identities_delete_identity/400_test.go @@ -17,7 +17,6 @@ func TestBadRequests(t *testing.T) { rootKey := h.CreateRootKey(h.Resources().UserWorkspace.ID, "identity.*.delete_identity") route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_delete_identity/401_test.go b/svc/api/routes/v2_identities_delete_identity/401_test.go index 445966fabe..cb34978ab4 100644 --- a/svc/api/routes/v2_identities_delete_identity/401_test.go +++ b/svc/api/routes/v2_identities_delete_identity/401_test.go @@ -16,7 +16,6 @@ func TestDeleteIdentityUnauthorized(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_delete_identity/403_test.go b/svc/api/routes/v2_identities_delete_identity/403_test.go index 2d1df79e45..977c9f055d 100644 --- a/svc/api/routes/v2_identities_delete_identity/403_test.go +++ b/svc/api/routes/v2_identities_delete_identity/403_test.go @@ -16,7 +16,6 @@ func TestDeleteIdentityForbidden(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_delete_identity/404_test.go b/svc/api/routes/v2_identities_delete_identity/404_test.go index 772704fd94..192adbdbe1 100644 --- a/svc/api/routes/v2_identities_delete_identity/404_test.go +++ b/svc/api/routes/v2_identities_delete_identity/404_test.go @@ -18,7 +18,6 @@ func TestDeleteIdentityNotFound(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_delete_identity/BUILD.bazel b/svc/api/routes/v2_identities_delete_identity/BUILD.bazel index ed59ab96a0..f1d04fbf56 100644 --- a/svc/api/routes/v2_identities_delete_identity/BUILD.bazel +++ b/svc/api/routes/v2_identities_delete_identity/BUILD.bazel @@ -12,7 +12,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_identities_delete_identity/handler.go b/svc/api/routes/v2_identities_delete_identity/handler.go index 10af06f300..c4675bcef5 100644 --- a/svc/api/routes/v2_identities_delete_identity/handler.go +++ b/svc/api/routes/v2_identities_delete_identity/handler.go @@ -12,7 +12,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -25,8 +24,6 @@ type ( // Handler implements zen.Route interface for the v2 identities delete identity endpoint type Handler struct { - // Services as public fields - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService diff --git a/svc/api/routes/v2_identities_get_identity/200_test.go b/svc/api/routes/v2_identities_get_identity/200_test.go index 90be8d3b23..de3ca1a803 100644 --- a/svc/api/routes/v2_identities_get_identity/200_test.go +++ b/svc/api/routes/v2_identities_get_identity/200_test.go @@ -23,9 +23,8 @@ import ( func TestSuccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_identities_get_identity/400_test.go b/svc/api/routes/v2_identities_get_identity/400_test.go index 889232e036..3ab2a6f222 100644 --- a/svc/api/routes/v2_identities_get_identity/400_test.go +++ b/svc/api/routes/v2_identities_get_identity/400_test.go @@ -15,9 +15,8 @@ import ( func TestBadRequests(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_identities_get_identity/401_test.go b/svc/api/routes/v2_identities_get_identity/401_test.go index 8242430dd4..84cdc50820 100644 --- a/svc/api/routes/v2_identities_get_identity/401_test.go +++ b/svc/api/routes/v2_identities_get_identity/401_test.go @@ -13,9 +13,8 @@ import ( func TestUnauthorized(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_identities_get_identity/403_test.go b/svc/api/routes/v2_identities_get_identity/403_test.go index 359482d78f..ca2a0930c0 100644 --- a/svc/api/routes/v2_identities_get_identity/403_test.go +++ b/svc/api/routes/v2_identities_get_identity/403_test.go @@ -21,9 +21,8 @@ import ( func TestForbidden(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_identities_get_identity/404_test.go b/svc/api/routes/v2_identities_get_identity/404_test.go index ab3fa6fdb1..0b09e75d24 100644 --- a/svc/api/routes/v2_identities_get_identity/404_test.go +++ b/svc/api/routes/v2_identities_get_identity/404_test.go @@ -20,9 +20,8 @@ import ( func TestNotFound(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_identities_get_identity/BUILD.bazel b/svc/api/routes/v2_identities_get_identity/BUILD.bazel index 5f60f2e405..88e672a1f6 100644 --- a/svc/api/routes/v2_identities_get_identity/BUILD.bazel +++ b/svc/api/routes/v2_identities_get_identity/BUILD.bazel @@ -10,7 +10,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_identities_get_identity/handler.go b/svc/api/routes/v2_identities_get_identity/handler.go index b33dc7ab18..2c4f268bf5 100644 --- a/svc/api/routes/v2_identities_get_identity/handler.go +++ b/svc/api/routes/v2_identities_get_identity/handler.go @@ -8,7 +8,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -21,10 +21,8 @@ type Response = openapi.V2IdentitiesGetIdentityResponseBody // Handler implements zen.Route interface for the v2 identities get identity endpoint type Handler struct { - // Services as public fields - Logger logging.Logger - DB db.Database - Keys keys.KeyService + DB db.Database + Keys keys.KeyService } // Method returns the HTTP method this route responds to @@ -72,7 +70,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { // Parse ratelimits JSON ratelimits, err := db.UnmarshalNullableJSONTo[[]db.RatelimitInfo](identity.Ratelimits) if err != nil { - h.Logger.Error("failed to unmarshal ratelimits", + logger.Error("failed to unmarshal ratelimits", "identityId", identity.ID, "error", err, ) @@ -97,7 +95,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { metaMap, err := db.UnmarshalNullableJSONTo[map[string]any](identity.Meta) if err != nil { - h.Logger.Error("failed to unmarshal identity meta", + logger.Error("failed to unmarshal identity meta", "identityId", identity.ID, "error", err, ) diff --git a/svc/api/routes/v2_identities_list_identities/200_test.go b/svc/api/routes/v2_identities_list_identities/200_test.go index e400b0ed09..e10cf18f26 100644 --- a/svc/api/routes/v2_identities_list_identities/200_test.go +++ b/svc/api/routes/v2_identities_list_identities/200_test.go @@ -20,9 +20,8 @@ import ( func TestSuccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } // Register the route with the harness diff --git a/svc/api/routes/v2_identities_list_identities/400_test.go b/svc/api/routes/v2_identities_list_identities/400_test.go index 827dd7a545..d27e724848 100644 --- a/svc/api/routes/v2_identities_list_identities/400_test.go +++ b/svc/api/routes/v2_identities_list_identities/400_test.go @@ -17,9 +17,8 @@ import ( func TestBadRequests(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } // Register the route with the harness diff --git a/svc/api/routes/v2_identities_list_identities/401_test.go b/svc/api/routes/v2_identities_list_identities/401_test.go index 28ff036797..e33892479e 100644 --- a/svc/api/routes/v2_identities_list_identities/401_test.go +++ b/svc/api/routes/v2_identities_list_identities/401_test.go @@ -13,9 +13,8 @@ import ( func TestUnauthorized(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } // Register the route with the harness diff --git a/svc/api/routes/v2_identities_list_identities/403_test.go b/svc/api/routes/v2_identities_list_identities/403_test.go index 8af402c906..a2f88973d8 100644 --- a/svc/api/routes/v2_identities_list_identities/403_test.go +++ b/svc/api/routes/v2_identities_list_identities/403_test.go @@ -20,9 +20,8 @@ import ( func TestForbidden(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } // Create a rootKey without any permissions diff --git a/svc/api/routes/v2_identities_list_identities/BUILD.bazel b/svc/api/routes/v2_identities_list_identities/BUILD.bazel index 401e1323d9..8d5ee6597c 100644 --- a/svc/api/routes/v2_identities_list_identities/BUILD.bazel +++ b/svc/api/routes/v2_identities_list_identities/BUILD.bazel @@ -9,7 +9,7 @@ go_library( "//internal/services/keys", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/ptr", "//pkg/rbac", "//pkg/zen", diff --git a/svc/api/routes/v2_identities_list_identities/cross_workspace_test.go b/svc/api/routes/v2_identities_list_identities/cross_workspace_test.go index 8404182ae8..40a006155a 100644 --- a/svc/api/routes/v2_identities_list_identities/cross_workspace_test.go +++ b/svc/api/routes/v2_identities_list_identities/cross_workspace_test.go @@ -19,9 +19,8 @@ import ( func TestCrossWorkspaceForbidden(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_identities_list_identities/handler.go b/svc/api/routes/v2_identities_list_identities/handler.go index 32e685ecef..829798e9a3 100644 --- a/svc/api/routes/v2_identities_list_identities/handler.go +++ b/svc/api/routes/v2_identities_list_identities/handler.go @@ -7,7 +7,7 @@ import ( "github.com/unkeyed/unkey/internal/services/keys" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" @@ -21,10 +21,8 @@ type ( // Handler implements zen.Route interface for the v2 identities list identities endpoint type Handler struct { - // Services as public fields - Logger logging.Logger - DB db.Database - Keys keys.KeyService + DB db.Database + Keys keys.KeyService } // Method returns the HTTP method this route responds to @@ -104,7 +102,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { // Unmarshal ratelimits from JSON ratelimits, err := db.UnmarshalNullableJSONTo[[]db.RatelimitInfo](identity.Ratelimits) if err != nil { - h.Logger.Error("failed to unmarshal identity ratelimits", + logger.Error("failed to unmarshal identity ratelimits", "identityId", identity.ID, "error", err, ) @@ -125,7 +123,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { // Unmarshal metadata metaMap, err := db.UnmarshalNullableJSONTo[map[string]any](identity.Meta) if err != nil { - h.Logger.Error("failed to unmarshal identity meta", + logger.Error("failed to unmarshal identity meta", "identityId", identity.ID, "error", err, ) diff --git a/svc/api/routes/v2_identities_update_identity/200_test.go b/svc/api/routes/v2_identities_update_identity/200_test.go index ce635af054..c70dd61295 100644 --- a/svc/api/routes/v2_identities_update_identity/200_test.go +++ b/svc/api/routes/v2_identities_update_identity/200_test.go @@ -21,7 +21,6 @@ import ( func TestSuccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, @@ -278,7 +277,6 @@ func TestUpdateIdentityConcurrentRatelimits(t *testing.T) { ctx := context.Background() route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_update_identity/400_test.go b/svc/api/routes/v2_identities_update_identity/400_test.go index 76247a1d8e..e41772e6ac 100644 --- a/svc/api/routes/v2_identities_update_identity/400_test.go +++ b/svc/api/routes/v2_identities_update_identity/400_test.go @@ -15,7 +15,6 @@ import ( func TestBadRequests(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_update_identity/401_test.go b/svc/api/routes/v2_identities_update_identity/401_test.go index b51cac4e80..fbe1a7d663 100644 --- a/svc/api/routes/v2_identities_update_identity/401_test.go +++ b/svc/api/routes/v2_identities_update_identity/401_test.go @@ -15,7 +15,6 @@ import ( func TestUnauthorized(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_update_identity/403_test.go b/svc/api/routes/v2_identities_update_identity/403_test.go index e928974243..60589465a9 100644 --- a/svc/api/routes/v2_identities_update_identity/403_test.go +++ b/svc/api/routes/v2_identities_update_identity/403_test.go @@ -20,7 +20,6 @@ import ( func TestForbidden(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_update_identity/404_test.go b/svc/api/routes/v2_identities_update_identity/404_test.go index 877007a56a..78a40a9688 100644 --- a/svc/api/routes/v2_identities_update_identity/404_test.go +++ b/svc/api/routes/v2_identities_update_identity/404_test.go @@ -15,7 +15,6 @@ import ( func TestNotFound(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_identities_update_identity/BUILD.bazel b/svc/api/routes/v2_identities_update_identity/BUILD.bazel index 93e57a7a46..0639010a28 100644 --- a/svc/api/routes/v2_identities_update_identity/BUILD.bazel +++ b/svc/api/routes/v2_identities_update_identity/BUILD.bazel @@ -12,7 +12,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/ptr", "//pkg/rbac", "//pkg/uid", diff --git a/svc/api/routes/v2_identities_update_identity/handler.go b/svc/api/routes/v2_identities_update_identity/handler.go index d4a959423d..a707980b22 100644 --- a/svc/api/routes/v2_identities_update_identity/handler.go +++ b/svc/api/routes/v2_identities_update_identity/handler.go @@ -14,7 +14,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" @@ -29,8 +28,6 @@ type ( // Handler implements zen.Route interface for the v2 identities update identity endpoint type Handler struct { - // Services as public fields - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService diff --git a/svc/api/routes/v2_keys_add_permissions/200_test.go b/svc/api/routes/v2_keys_add_permissions/200_test.go index fda65dd4ac..1b8d69e16d 100644 --- a/svc/api/routes/v2_keys_add_permissions/200_test.go +++ b/svc/api/routes/v2_keys_add_permissions/200_test.go @@ -22,7 +22,6 @@ func TestSuccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } @@ -313,7 +312,6 @@ func TestAddPermissionsConcurrent(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_add_permissions/400_test.go b/svc/api/routes/v2_keys_add_permissions/400_test.go index 3300f0d146..69b9147c2e 100644 --- a/svc/api/routes/v2_keys_add_permissions/400_test.go +++ b/svc/api/routes/v2_keys_add_permissions/400_test.go @@ -25,7 +25,6 @@ func TestValidationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_add_permissions/401_test.go b/svc/api/routes/v2_keys_add_permissions/401_test.go index ddc57e8782..2ae125ce74 100644 --- a/svc/api/routes/v2_keys_add_permissions/401_test.go +++ b/svc/api/routes/v2_keys_add_permissions/401_test.go @@ -23,7 +23,6 @@ func TestAuthenticationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_add_permissions/403_test.go b/svc/api/routes/v2_keys_add_permissions/403_test.go index 58f0aaec19..b64fda1d8b 100644 --- a/svc/api/routes/v2_keys_add_permissions/403_test.go +++ b/svc/api/routes/v2_keys_add_permissions/403_test.go @@ -23,7 +23,6 @@ func TestAuthorizationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_add_permissions/404_test.go b/svc/api/routes/v2_keys_add_permissions/404_test.go index 0c162f3163..a361607e29 100644 --- a/svc/api/routes/v2_keys_add_permissions/404_test.go +++ b/svc/api/routes/v2_keys_add_permissions/404_test.go @@ -24,7 +24,6 @@ func TestNotFoundErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_add_permissions/BUILD.bazel b/svc/api/routes/v2_keys_add_permissions/BUILD.bazel index b0b255d66a..d79413038f 100644 --- a/svc/api/routes/v2_keys_add_permissions/BUILD.bazel +++ b/svc/api/routes/v2_keys_add_permissions/BUILD.bazel @@ -14,7 +14,6 @@ go_library( "//pkg/db", "//pkg/db/types", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/uid", "//pkg/zen", diff --git a/svc/api/routes/v2_keys_add_permissions/handler.go b/svc/api/routes/v2_keys_add_permissions/handler.go index 1243812a68..8ec8fe354e 100644 --- a/svc/api/routes/v2_keys_add_permissions/handler.go +++ b/svc/api/routes/v2_keys_add_permissions/handler.go @@ -15,7 +15,6 @@ import ( "github.com/unkeyed/unkey/pkg/db" dbtype "github.com/unkeyed/unkey/pkg/db/types" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/pkg/zen" @@ -26,7 +25,6 @@ type Request = openapi.V2KeysAddPermissionsRequestBody type Response = openapi.V2KeysAddPermissionsResponseBody type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService diff --git a/svc/api/routes/v2_keys_add_roles/200_test.go b/svc/api/routes/v2_keys_add_roles/200_test.go index e640e84479..b9561e9118 100644 --- a/svc/api/routes/v2_keys_add_roles/200_test.go +++ b/svc/api/routes/v2_keys_add_roles/200_test.go @@ -21,7 +21,6 @@ func TestSuccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, @@ -172,7 +171,6 @@ func TestAddRolesConcurrent(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_add_roles/400_test.go b/svc/api/routes/v2_keys_add_roles/400_test.go index ac3429d04d..4e3fae4adf 100644 --- a/svc/api/routes/v2_keys_add_roles/400_test.go +++ b/svc/api/routes/v2_keys_add_roles/400_test.go @@ -16,7 +16,6 @@ func TestValidationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_add_roles/401_test.go b/svc/api/routes/v2_keys_add_roles/401_test.go index 9377ef65c4..2d86ae4632 100644 --- a/svc/api/routes/v2_keys_add_roles/401_test.go +++ b/svc/api/routes/v2_keys_add_roles/401_test.go @@ -16,7 +16,6 @@ func TestAuthenticationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_add_roles/403_test.go b/svc/api/routes/v2_keys_add_roles/403_test.go index 00421ffa75..d66683c0c1 100644 --- a/svc/api/routes/v2_keys_add_roles/403_test.go +++ b/svc/api/routes/v2_keys_add_roles/403_test.go @@ -23,7 +23,6 @@ func TestAuthorizationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_add_roles/404_test.go b/svc/api/routes/v2_keys_add_roles/404_test.go index 17fbc407db..8f05e7ba4a 100644 --- a/svc/api/routes/v2_keys_add_roles/404_test.go +++ b/svc/api/routes/v2_keys_add_roles/404_test.go @@ -22,7 +22,6 @@ func TestNotFoundErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_add_roles/BUILD.bazel b/svc/api/routes/v2_keys_add_roles/BUILD.bazel index cbc91c80a2..fd94db7f46 100644 --- a/svc/api/routes/v2_keys_add_roles/BUILD.bazel +++ b/svc/api/routes/v2_keys_add_roles/BUILD.bazel @@ -13,7 +13,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_keys_add_roles/handler.go b/svc/api/routes/v2_keys_add_roles/handler.go index b37c527ecf..3abdde5eb4 100644 --- a/svc/api/routes/v2_keys_add_roles/handler.go +++ b/svc/api/routes/v2_keys_add_roles/handler.go @@ -13,7 +13,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -25,7 +25,6 @@ type ( ) type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -44,8 +43,6 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/keys.addRoles") - auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() if err != nil { @@ -245,7 +242,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { rolePermissions, err := db.UnmarshalNullableJSONTo[[]db.Permission](role.Permissions) if err != nil { - h.Logger.Error("Failed to unmarshal role permissions", "error", err) + logger.Error("Failed to unmarshal role permissions", "error", err) } for _, permission := range rolePermissions { diff --git a/svc/api/routes/v2_keys_create_key/200_test.go b/svc/api/routes/v2_keys_create_key/200_test.go index cbc9fcc2e0..bc88db3c88 100644 --- a/svc/api/routes/v2_keys_create_key/200_test.go +++ b/svc/api/routes/v2_keys_create_key/200_test.go @@ -25,7 +25,6 @@ func TestCreateKeySuccess(t *testing.T) { ctx := context.Background() route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, @@ -78,7 +77,6 @@ func TestCreateKeyWithOptionalFields(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } @@ -141,7 +139,6 @@ func TestCreateKeyWithEncryption(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } @@ -205,7 +202,6 @@ func TestCreateKeyConcurrentWithSameExternalId(t *testing.T) { ctx := t.Context() route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, @@ -285,7 +281,6 @@ func TestCreateKeyWithCreditsRemainingNull(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_create_key/400_test.go b/svc/api/routes/v2_keys_create_key/400_test.go index 576bc4d3ed..6af6d8b0ef 100644 --- a/svc/api/routes/v2_keys_create_key/400_test.go +++ b/svc/api/routes/v2_keys_create_key/400_test.go @@ -22,7 +22,6 @@ func TestCreateKeyBadRequest(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_create_key/401_test.go b/svc/api/routes/v2_keys_create_key/401_test.go index 394a909c81..0172d1ae64 100644 --- a/svc/api/routes/v2_keys_create_key/401_test.go +++ b/svc/api/routes/v2_keys_create_key/401_test.go @@ -19,7 +19,6 @@ func TestCreateKeyUnauthorized(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_create_key/403_test.go b/svc/api/routes/v2_keys_create_key/403_test.go index 8d173ba2e4..3f2bb41f89 100644 --- a/svc/api/routes/v2_keys_create_key/403_test.go +++ b/svc/api/routes/v2_keys_create_key/403_test.go @@ -25,7 +25,6 @@ func TestCreateKeyForbidden(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_create_key/404_test.go b/svc/api/routes/v2_keys_create_key/404_test.go index f47ffcd1f6..9a998dc21f 100644 --- a/svc/api/routes/v2_keys_create_key/404_test.go +++ b/svc/api/routes/v2_keys_create_key/404_test.go @@ -19,7 +19,6 @@ func TestCreateKeyNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_create_key/412_test.go b/svc/api/routes/v2_keys_create_key/412_test.go index 5a19d34c1a..213f5e208c 100644 --- a/svc/api/routes/v2_keys_create_key/412_test.go +++ b/svc/api/routes/v2_keys_create_key/412_test.go @@ -22,7 +22,6 @@ func TestPreconditionError(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Vault: h.Vault, diff --git a/svc/api/routes/v2_keys_create_key/BUILD.bazel b/svc/api/routes/v2_keys_create_key/BUILD.bazel index c8d783ac69..fc16359ed6 100644 --- a/svc/api/routes/v2_keys_create_key/BUILD.bazel +++ b/svc/api/routes/v2_keys_create_key/BUILD.bazel @@ -14,7 +14,6 @@ go_library( "//pkg/db", "//pkg/db/types", "//pkg/fault", - "//pkg/otel/logging", "//pkg/ptr", "//pkg/rbac", "//pkg/uid", diff --git a/svc/api/routes/v2_keys_create_key/handler.go b/svc/api/routes/v2_keys_create_key/handler.go index 93583a95d7..8bc1e82cd2 100644 --- a/svc/api/routes/v2_keys_create_key/handler.go +++ b/svc/api/routes/v2_keys_create_key/handler.go @@ -19,7 +19,6 @@ import ( "github.com/unkeyed/unkey/pkg/db" dbtype "github.com/unkeyed/unkey/pkg/db/types" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" @@ -33,7 +32,6 @@ type ( ) type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -52,8 +50,6 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/keys.createKey") - // 1. Authentication auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() diff --git a/svc/api/routes/v2_keys_delete_key/200_test.go b/svc/api/routes/v2_keys_delete_key/200_test.go index decf1c31cb..15d3346f24 100644 --- a/svc/api/routes/v2_keys_delete_key/200_test.go +++ b/svc/api/routes/v2_keys_delete_key/200_test.go @@ -22,7 +22,6 @@ func TestKeyDeleteSuccess(t *testing.T) { ctx := context.Background() route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_delete_key/400_test.go b/svc/api/routes/v2_keys_delete_key/400_test.go index 08781e0067..407f3e3429 100644 --- a/svc/api/routes/v2_keys_delete_key/400_test.go +++ b/svc/api/routes/v2_keys_delete_key/400_test.go @@ -17,7 +17,6 @@ func TestKeyDeleteBadRequest(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_delete_key/401_test.go b/svc/api/routes/v2_keys_delete_key/401_test.go index 32072773af..35d657cb22 100644 --- a/svc/api/routes/v2_keys_delete_key/401_test.go +++ b/svc/api/routes/v2_keys_delete_key/401_test.go @@ -22,7 +22,6 @@ func TestKeyDeleteUnauthorized(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_delete_key/403_test.go b/svc/api/routes/v2_keys_delete_key/403_test.go index d0924a1c54..3fccbdf786 100644 --- a/svc/api/routes/v2_keys_delete_key/403_test.go +++ b/svc/api/routes/v2_keys_delete_key/403_test.go @@ -25,7 +25,6 @@ func TestKeyDeleteForbidden(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_delete_key/404_test.go b/svc/api/routes/v2_keys_delete_key/404_test.go index 8bb149e7b0..2971dfd3c5 100644 --- a/svc/api/routes/v2_keys_delete_key/404_test.go +++ b/svc/api/routes/v2_keys_delete_key/404_test.go @@ -23,7 +23,6 @@ func TestKeyDeleteNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_delete_key/BUILD.bazel b/svc/api/routes/v2_keys_delete_key/BUILD.bazel index 206cdf4ea7..c15d11cef9 100644 --- a/svc/api/routes/v2_keys_delete_key/BUILD.bazel +++ b/svc/api/routes/v2_keys_delete_key/BUILD.bazel @@ -13,7 +13,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/ptr", "//pkg/rbac", "//pkg/zen", diff --git a/svc/api/routes/v2_keys_delete_key/handler.go b/svc/api/routes/v2_keys_delete_key/handler.go index 8fba7b2292..a83527be4c 100644 --- a/svc/api/routes/v2_keys_delete_key/handler.go +++ b/svc/api/routes/v2_keys_delete_key/handler.go @@ -14,7 +14,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" @@ -26,7 +25,6 @@ type Response = openapi.V2KeysDeleteKeyResponseBody // Handler implements zen.Route interface for the v2 keys.deleteKey endpoint type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -44,8 +42,6 @@ func (h *Handler) Path() string { } func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/keys.deleteKey") - // Authentication auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() diff --git a/svc/api/routes/v2_keys_get_key/200_test.go b/svc/api/routes/v2_keys_get_key/200_test.go index 4e8b3a7fc9..bb33005918 100644 --- a/svc/api/routes/v2_keys_get_key/200_test.go +++ b/svc/api/routes/v2_keys_get_key/200_test.go @@ -25,7 +25,6 @@ func TestGetKeyByKeyID(t *testing.T) { ctx := context.Background() route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, @@ -124,7 +123,6 @@ func TestGetKeyByKeyID(t *testing.T) { func TestGetKey_AdditionalScenarios(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_get_key/400_test.go b/svc/api/routes/v2_keys_get_key/400_test.go index 7396bcebd8..20c85080c9 100644 --- a/svc/api/routes/v2_keys_get_key/400_test.go +++ b/svc/api/routes/v2_keys_get_key/400_test.go @@ -18,7 +18,6 @@ func TestGetKeyBadRequest(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_get_key/401_test.go b/svc/api/routes/v2_keys_get_key/401_test.go index c8cb143f2e..ecb0956b5c 100644 --- a/svc/api/routes/v2_keys_get_key/401_test.go +++ b/svc/api/routes/v2_keys_get_key/401_test.go @@ -18,7 +18,6 @@ func TestGetKeyUnauthorized(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_get_key/403_test.go b/svc/api/routes/v2_keys_get_key/403_test.go index b419d2c036..5d281d709a 100644 --- a/svc/api/routes/v2_keys_get_key/403_test.go +++ b/svc/api/routes/v2_keys_get_key/403_test.go @@ -25,7 +25,6 @@ func TestGetKeyForbidden(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_get_key/404_test.go b/svc/api/routes/v2_keys_get_key/404_test.go index 6a98575d35..486568e31f 100644 --- a/svc/api/routes/v2_keys_get_key/404_test.go +++ b/svc/api/routes/v2_keys_get_key/404_test.go @@ -20,7 +20,6 @@ func TestGetKeyNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_get_key/412_test.go b/svc/api/routes/v2_keys_get_key/412_test.go index 956ca19845..9ed28bc5f7 100644 --- a/svc/api/routes/v2_keys_get_key/412_test.go +++ b/svc/api/routes/v2_keys_get_key/412_test.go @@ -17,10 +17,9 @@ func TestPreconditionError(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, - DB: h.DB, - Keys: h.Keys, - Vault: h.Vault, + DB: h.DB, + Keys: h.Keys, + Vault: h.Vault, } h.Register(route) @@ -87,7 +86,6 @@ func TestPreconditionError(t *testing.T) { }) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, @@ -138,7 +136,6 @@ func TestPreconditionError(t *testing.T) { // Create route with nil vault routeNoVault := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_get_key/500_test.go b/svc/api/routes/v2_keys_get_key/500_test.go index f4ee15878e..408a974b58 100644 --- a/svc/api/routes/v2_keys_get_key/500_test.go +++ b/svc/api/routes/v2_keys_get_key/500_test.go @@ -16,7 +16,6 @@ import ( func TestInternalError(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_get_key/BUILD.bazel b/svc/api/routes/v2_keys_get_key/BUILD.bazel index cf78a659a3..3311e62770 100644 --- a/svc/api/routes/v2_keys_get_key/BUILD.bazel +++ b/svc/api/routes/v2_keys_get_key/BUILD.bazel @@ -12,7 +12,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/ptr", "//pkg/rbac", "//pkg/vault", diff --git a/svc/api/routes/v2_keys_get_key/handler.go b/svc/api/routes/v2_keys_get_key/handler.go index 632d190160..dec346b88f 100644 --- a/svc/api/routes/v2_keys_get_key/handler.go +++ b/svc/api/routes/v2_keys_get_key/handler.go @@ -11,7 +11,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/vault" @@ -26,7 +26,6 @@ type ( // Handler implements zen.Route interface for the v2 keys.getKey endpoint type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -42,8 +41,6 @@ func (h *Handler) Path() string { } func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/keys.getKey") - // Authentication auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() @@ -173,7 +170,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { identityMeta, getMetaError := db.UnmarshalNullableJSONTo[map[string]any](keyData.Identity.Meta) response.Identity.Meta = identityMeta if getMetaError != nil { - h.Logger.Error("failed to unmarshal identity meta", "error", err) + logger.Error("failed to unmarshal identity meta", "error", err) } } } @@ -230,7 +227,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { // Set meta meta, err := db.UnmarshalNullableJSONTo[map[string]any](keyData.Key.Meta.String) if err != nil { - h.Logger.Error("failed to unmarshal key meta", + logger.Error("failed to unmarshal key meta", "keyId", keyData.Key.ID, "error", err, ) @@ -289,7 +286,7 @@ func (h *Handler) decryptKey(ctx context.Context, auth *keys.KeyVerifier, keyDat Encrypted: keyData.EncryptedKey.String, }) if err != nil { - h.Logger.Error("failed to decrypt key", + logger.Error("failed to decrypt key", "keyId", keyData.Key.ID, "error", err, ) diff --git a/svc/api/routes/v2_keys_migrate_keys/200_test.go b/svc/api/routes/v2_keys_migrate_keys/200_test.go index 50f90f5633..213a0da406 100644 --- a/svc/api/routes/v2_keys_migrate_keys/200_test.go +++ b/svc/api/routes/v2_keys_migrate_keys/200_test.go @@ -25,7 +25,6 @@ func TestMigrateKeysSuccess(t *testing.T) { ctx := context.Background() route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_migrate_keys/400_test.go b/svc/api/routes/v2_keys_migrate_keys/400_test.go index 7b18d0f82d..76edfbd3c3 100644 --- a/svc/api/routes/v2_keys_migrate_keys/400_test.go +++ b/svc/api/routes/v2_keys_migrate_keys/400_test.go @@ -21,7 +21,6 @@ func TestMigrateKeysBadRequest(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ApiCache: h.Caches.LiveApiByID, } diff --git a/svc/api/routes/v2_keys_migrate_keys/401_test.go b/svc/api/routes/v2_keys_migrate_keys/401_test.go index 7652ddd579..7390447268 100644 --- a/svc/api/routes/v2_keys_migrate_keys/401_test.go +++ b/svc/api/routes/v2_keys_migrate_keys/401_test.go @@ -21,7 +21,6 @@ func TestMigrateKeysUnauthorized(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ApiCache: h.Caches.LiveApiByID, } diff --git a/svc/api/routes/v2_keys_migrate_keys/403_test.go b/svc/api/routes/v2_keys_migrate_keys/403_test.go index a9b509468d..ef66c2b831 100644 --- a/svc/api/routes/v2_keys_migrate_keys/403_test.go +++ b/svc/api/routes/v2_keys_migrate_keys/403_test.go @@ -19,7 +19,6 @@ func TestMigrateKeysForbidden(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ApiCache: h.Caches.LiveApiByID, } diff --git a/svc/api/routes/v2_keys_migrate_keys/404_test.go b/svc/api/routes/v2_keys_migrate_keys/404_test.go index 92e19fd641..ec21147c14 100644 --- a/svc/api/routes/v2_keys_migrate_keys/404_test.go +++ b/svc/api/routes/v2_keys_migrate_keys/404_test.go @@ -22,7 +22,6 @@ func TestMigrateKeysNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, - Logger: h.Logger, Keys: h.Keys, Auditlogs: h.Auditlogs, ApiCache: h.Caches.LiveApiByID, diff --git a/svc/api/routes/v2_keys_migrate_keys/BUILD.bazel b/svc/api/routes/v2_keys_migrate_keys/BUILD.bazel index dfac15c9c1..ffde019444 100644 --- a/svc/api/routes/v2_keys_migrate_keys/BUILD.bazel +++ b/svc/api/routes/v2_keys_migrate_keys/BUILD.bazel @@ -15,7 +15,6 @@ go_library( "//pkg/db", "//pkg/db/types", "//pkg/fault", - "//pkg/otel/logging", "//pkg/ptr", "//pkg/rbac", "//pkg/uid", diff --git a/svc/api/routes/v2_keys_migrate_keys/handler.go b/svc/api/routes/v2_keys_migrate_keys/handler.go index db5ee22300..3b4779b339 100644 --- a/svc/api/routes/v2_keys_migrate_keys/handler.go +++ b/svc/api/routes/v2_keys_migrate_keys/handler.go @@ -19,7 +19,6 @@ import ( "github.com/unkeyed/unkey/pkg/db" dbtype "github.com/unkeyed/unkey/pkg/db/types" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" @@ -36,7 +35,6 @@ const ( ) type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -55,8 +53,6 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/keys.migrateKeys") - auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() if err != nil { diff --git a/svc/api/routes/v2_keys_remove_permissions/200_test.go b/svc/api/routes/v2_keys_remove_permissions/200_test.go index e3eb614c50..f2a1aced47 100644 --- a/svc/api/routes/v2_keys_remove_permissions/200_test.go +++ b/svc/api/routes/v2_keys_remove_permissions/200_test.go @@ -23,7 +23,6 @@ func TestSuccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_remove_permissions/400_test.go b/svc/api/routes/v2_keys_remove_permissions/400_test.go index 4028673c33..884a67203b 100644 --- a/svc/api/routes/v2_keys_remove_permissions/400_test.go +++ b/svc/api/routes/v2_keys_remove_permissions/400_test.go @@ -23,7 +23,6 @@ func TestValidationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_remove_permissions/401_test.go b/svc/api/routes/v2_keys_remove_permissions/401_test.go index 54eeff4784..9fe5676579 100644 --- a/svc/api/routes/v2_keys_remove_permissions/401_test.go +++ b/svc/api/routes/v2_keys_remove_permissions/401_test.go @@ -18,7 +18,6 @@ func TestAuthenticationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_remove_permissions/403_test.go b/svc/api/routes/v2_keys_remove_permissions/403_test.go index a125cd1370..8705712e00 100644 --- a/svc/api/routes/v2_keys_remove_permissions/403_test.go +++ b/svc/api/routes/v2_keys_remove_permissions/403_test.go @@ -23,7 +23,6 @@ func TestAuthorizationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_remove_permissions/404_test.go b/svc/api/routes/v2_keys_remove_permissions/404_test.go index 1a7c7a0a6d..0d3d3b2dd0 100644 --- a/svc/api/routes/v2_keys_remove_permissions/404_test.go +++ b/svc/api/routes/v2_keys_remove_permissions/404_test.go @@ -26,7 +26,6 @@ func TestNotFoundErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_remove_permissions/BUILD.bazel b/svc/api/routes/v2_keys_remove_permissions/BUILD.bazel index f2accd8fa6..cb83ca1f29 100644 --- a/svc/api/routes/v2_keys_remove_permissions/BUILD.bazel +++ b/svc/api/routes/v2_keys_remove_permissions/BUILD.bazel @@ -13,7 +13,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_keys_remove_permissions/handler.go b/svc/api/routes/v2_keys_remove_permissions/handler.go index 26e5320690..0fd8a12624 100644 --- a/svc/api/routes/v2_keys_remove_permissions/handler.go +++ b/svc/api/routes/v2_keys_remove_permissions/handler.go @@ -12,7 +12,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -23,8 +22,6 @@ type Response = openapi.V2KeysRemovePermissionsResponseBody // Handler implements zen.Route interface for the v2 keys remove permissions endpoint type Handler struct { - // Services as public fields - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -43,8 +40,6 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/keys.removePermissions") - // 1. Authentication auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() diff --git a/svc/api/routes/v2_keys_remove_roles/200_test.go b/svc/api/routes/v2_keys_remove_roles/200_test.go index 52bd42c56a..a69410819c 100644 --- a/svc/api/routes/v2_keys_remove_roles/200_test.go +++ b/svc/api/routes/v2_keys_remove_roles/200_test.go @@ -23,7 +23,6 @@ func TestSuccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_remove_roles/400_test.go b/svc/api/routes/v2_keys_remove_roles/400_test.go index 8c9dbf59c2..73b7a734df 100644 --- a/svc/api/routes/v2_keys_remove_roles/400_test.go +++ b/svc/api/routes/v2_keys_remove_roles/400_test.go @@ -23,7 +23,6 @@ func TestValidationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_remove_roles/401_test.go b/svc/api/routes/v2_keys_remove_roles/401_test.go index 8275d64da0..3c63f67a15 100644 --- a/svc/api/routes/v2_keys_remove_roles/401_test.go +++ b/svc/api/routes/v2_keys_remove_roles/401_test.go @@ -23,7 +23,6 @@ func TestAuthenticationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_remove_roles/403_test.go b/svc/api/routes/v2_keys_remove_roles/403_test.go index 4110fa7600..d6f4a1d35e 100644 --- a/svc/api/routes/v2_keys_remove_roles/403_test.go +++ b/svc/api/routes/v2_keys_remove_roles/403_test.go @@ -23,7 +23,6 @@ func TestAuthorizationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_remove_roles/404_test.go b/svc/api/routes/v2_keys_remove_roles/404_test.go index 077260d27e..d615ac6e64 100644 --- a/svc/api/routes/v2_keys_remove_roles/404_test.go +++ b/svc/api/routes/v2_keys_remove_roles/404_test.go @@ -23,7 +23,6 @@ func TestNotFoundErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_remove_roles/BUILD.bazel b/svc/api/routes/v2_keys_remove_roles/BUILD.bazel index 931aeda625..bf3a9ee96c 100644 --- a/svc/api/routes/v2_keys_remove_roles/BUILD.bazel +++ b/svc/api/routes/v2_keys_remove_roles/BUILD.bazel @@ -13,7 +13,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_keys_remove_roles/handler.go b/svc/api/routes/v2_keys_remove_roles/handler.go index 17bcb36df3..b3f6c652cb 100644 --- a/svc/api/routes/v2_keys_remove_roles/handler.go +++ b/svc/api/routes/v2_keys_remove_roles/handler.go @@ -12,7 +12,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -25,7 +25,6 @@ type ( // Handler implements zen.Route interface for the v2 keys remove roles endpoint type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -44,8 +43,6 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/keys.removeRoles") - // 1. Authentication auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() @@ -219,7 +216,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { rolePermissions, err := db.UnmarshalNullableJSONTo[[]db.Permission](role.Permissions) if err != nil { - h.Logger.Error("Failed to unmarshal role permissions", "error", err) + logger.Error("Failed to unmarshal role permissions", "error", err) } for _, permission := range rolePermissions { diff --git a/svc/api/routes/v2_keys_reroll_key/200_test.go b/svc/api/routes/v2_keys_reroll_key/200_test.go index f3fe0c3944..b12d277870 100644 --- a/svc/api/routes/v2_keys_reroll_key/200_test.go +++ b/svc/api/routes/v2_keys_reroll_key/200_test.go @@ -21,7 +21,6 @@ func TestRerollKeySuccess(t *testing.T) { ctx := t.Context() route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_reroll_key/400_test.go b/svc/api/routes/v2_keys_reroll_key/400_test.go index b162f7b599..b4221143e2 100644 --- a/svc/api/routes/v2_keys_reroll_key/400_test.go +++ b/svc/api/routes/v2_keys_reroll_key/400_test.go @@ -19,7 +19,6 @@ func TestRerollKeyBadRequest(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_reroll_key/401_test.go b/svc/api/routes/v2_keys_reroll_key/401_test.go index fd27a45e04..0756d4ee99 100644 --- a/svc/api/routes/v2_keys_reroll_key/401_test.go +++ b/svc/api/routes/v2_keys_reroll_key/401_test.go @@ -20,7 +20,6 @@ func TestRerollKeyUnauthorized(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_reroll_key/403_test.go b/svc/api/routes/v2_keys_reroll_key/403_test.go index ea708094a9..c67f90f477 100644 --- a/svc/api/routes/v2_keys_reroll_key/403_test.go +++ b/svc/api/routes/v2_keys_reroll_key/403_test.go @@ -18,7 +18,6 @@ func TestRerollKeyForbidden(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_reroll_key/404_test.go b/svc/api/routes/v2_keys_reroll_key/404_test.go index 8b0c6d06cf..9334270f72 100644 --- a/svc/api/routes/v2_keys_reroll_key/404_test.go +++ b/svc/api/routes/v2_keys_reroll_key/404_test.go @@ -18,7 +18,6 @@ func TestRerollKeyNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_reroll_key/BUILD.bazel b/svc/api/routes/v2_keys_reroll_key/BUILD.bazel index 43ee691710..b9b468297e 100644 --- a/svc/api/routes/v2_keys_reroll_key/BUILD.bazel +++ b/svc/api/routes/v2_keys_reroll_key/BUILD.bazel @@ -13,7 +13,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/uid", "//pkg/vault", diff --git a/svc/api/routes/v2_keys_reroll_key/handler.go b/svc/api/routes/v2_keys_reroll_key/handler.go index b4547fdb27..543a4db166 100644 --- a/svc/api/routes/v2_keys_reroll_key/handler.go +++ b/svc/api/routes/v2_keys_reroll_key/handler.go @@ -17,7 +17,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/pkg/vault" @@ -30,7 +29,6 @@ type ( ) type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -49,8 +47,6 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/keys.rerollKey") - auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() if err != nil { diff --git a/svc/api/routes/v2_keys_set_permissions/200_test.go b/svc/api/routes/v2_keys_set_permissions/200_test.go index 0498dad46c..aa1e08bea1 100644 --- a/svc/api/routes/v2_keys_set_permissions/200_test.go +++ b/svc/api/routes/v2_keys_set_permissions/200_test.go @@ -25,7 +25,6 @@ func TestSuccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } @@ -445,7 +444,6 @@ func TestSetPermissionsConcurrent(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_set_permissions/400_test.go b/svc/api/routes/v2_keys_set_permissions/400_test.go index 12ba010e74..fe382058bd 100644 --- a/svc/api/routes/v2_keys_set_permissions/400_test.go +++ b/svc/api/routes/v2_keys_set_permissions/400_test.go @@ -18,7 +18,6 @@ func TestBadRequest(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_set_permissions/401_test.go b/svc/api/routes/v2_keys_set_permissions/401_test.go index dade3f0be6..1d4caada8e 100644 --- a/svc/api/routes/v2_keys_set_permissions/401_test.go +++ b/svc/api/routes/v2_keys_set_permissions/401_test.go @@ -25,7 +25,6 @@ func TestAuthenticationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_set_permissions/403_test.go b/svc/api/routes/v2_keys_set_permissions/403_test.go index bd1456e412..e21ccbec50 100644 --- a/svc/api/routes/v2_keys_set_permissions/403_test.go +++ b/svc/api/routes/v2_keys_set_permissions/403_test.go @@ -23,7 +23,6 @@ func TestForbidden(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_set_permissions/404_test.go b/svc/api/routes/v2_keys_set_permissions/404_test.go index 337555686f..0cc6ded573 100644 --- a/svc/api/routes/v2_keys_set_permissions/404_test.go +++ b/svc/api/routes/v2_keys_set_permissions/404_test.go @@ -23,7 +23,6 @@ func TestNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_set_permissions/BUILD.bazel b/svc/api/routes/v2_keys_set_permissions/BUILD.bazel index 0ef15e77ac..86844d5556 100644 --- a/svc/api/routes/v2_keys_set_permissions/BUILD.bazel +++ b/svc/api/routes/v2_keys_set_permissions/BUILD.bazel @@ -14,7 +14,6 @@ go_library( "//pkg/db", "//pkg/db/types", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/uid", "//pkg/zen", diff --git a/svc/api/routes/v2_keys_set_permissions/handler.go b/svc/api/routes/v2_keys_set_permissions/handler.go index 10eca17cf0..b4fe23704f 100644 --- a/svc/api/routes/v2_keys_set_permissions/handler.go +++ b/svc/api/routes/v2_keys_set_permissions/handler.go @@ -15,7 +15,6 @@ import ( "github.com/unkeyed/unkey/pkg/db" dbtype "github.com/unkeyed/unkey/pkg/db/types" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/pkg/zen" @@ -29,7 +28,6 @@ type ( // Handler implements zen.Route interface for the v2 keys set permissions endpoint type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -48,8 +46,6 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/keys.setPermissions") - // 1. Authentication auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() diff --git a/svc/api/routes/v2_keys_set_roles/200_test.go b/svc/api/routes/v2_keys_set_roles/200_test.go index d924968364..19921e8ffd 100644 --- a/svc/api/routes/v2_keys_set_roles/200_test.go +++ b/svc/api/routes/v2_keys_set_roles/200_test.go @@ -25,7 +25,6 @@ func TestSuccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } @@ -364,7 +363,6 @@ func TestSetRolesConcurrent(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_set_roles/400_test.go b/svc/api/routes/v2_keys_set_roles/400_test.go index 5cf9adf5e2..124d367862 100644 --- a/svc/api/routes/v2_keys_set_roles/400_test.go +++ b/svc/api/routes/v2_keys_set_roles/400_test.go @@ -17,7 +17,6 @@ func TestValidationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_set_roles/401_test.go b/svc/api/routes/v2_keys_set_roles/401_test.go index 45095b7a09..3c47d5df7e 100644 --- a/svc/api/routes/v2_keys_set_roles/401_test.go +++ b/svc/api/routes/v2_keys_set_roles/401_test.go @@ -16,7 +16,6 @@ func TestAuthenticationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_set_roles/403_test.go b/svc/api/routes/v2_keys_set_roles/403_test.go index 0b56786ca2..a3ff6330fa 100644 --- a/svc/api/routes/v2_keys_set_roles/403_test.go +++ b/svc/api/routes/v2_keys_set_roles/403_test.go @@ -18,7 +18,6 @@ func TestAuthorizationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_set_roles/404_test.go b/svc/api/routes/v2_keys_set_roles/404_test.go index a2cf5a0652..2924b1ed88 100644 --- a/svc/api/routes/v2_keys_set_roles/404_test.go +++ b/svc/api/routes/v2_keys_set_roles/404_test.go @@ -25,7 +25,6 @@ func TestNotFoundErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, } diff --git a/svc/api/routes/v2_keys_set_roles/BUILD.bazel b/svc/api/routes/v2_keys_set_roles/BUILD.bazel index c995d9a597..56f052a945 100644 --- a/svc/api/routes/v2_keys_set_roles/BUILD.bazel +++ b/svc/api/routes/v2_keys_set_roles/BUILD.bazel @@ -13,7 +13,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_keys_set_roles/handler.go b/svc/api/routes/v2_keys_set_roles/handler.go index bccc0dce42..8613d4ae77 100644 --- a/svc/api/routes/v2_keys_set_roles/handler.go +++ b/svc/api/routes/v2_keys_set_roles/handler.go @@ -13,7 +13,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -26,7 +26,6 @@ type ( // Handler implements zen.Route interface for the v2 keys set roles endpoint type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -45,8 +44,6 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/keys.setRoles") - auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() if err != nil { @@ -292,7 +289,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { rolePerms, err := db.UnmarshalNullableJSONTo[[]db.Permission](role.Permissions) if err != nil { - h.Logger.Error("failed to unmarshal role permissions", "roleId", role.ID, "error", err) + logger.Error("failed to unmarshal role permissions", "roleId", role.ID, "error", err) } for _, permission := range rolePerms { diff --git a/svc/api/routes/v2_keys_update_credits/200_test.go b/svc/api/routes/v2_keys_update_credits/200_test.go index a23cb01cca..ab95c780cd 100644 --- a/svc/api/routes/v2_keys_update_credits/200_test.go +++ b/svc/api/routes/v2_keys_update_credits/200_test.go @@ -24,7 +24,6 @@ func TestKeyUpdateCreditsSuccess(t *testing.T) { ctx := context.Background() route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_update_credits/400_test.go b/svc/api/routes/v2_keys_update_credits/400_test.go index 984d41758b..bbbccc5480 100644 --- a/svc/api/routes/v2_keys_update_credits/400_test.go +++ b/svc/api/routes/v2_keys_update_credits/400_test.go @@ -19,7 +19,6 @@ func TestKeyUpdateCreditsBadRequest(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, diff --git a/svc/api/routes/v2_keys_update_credits/401_test.go b/svc/api/routes/v2_keys_update_credits/401_test.go index 9b0de87faf..a6f7a43a91 100644 --- a/svc/api/routes/v2_keys_update_credits/401_test.go +++ b/svc/api/routes/v2_keys_update_credits/401_test.go @@ -19,7 +19,6 @@ func TestKeyUpdateCreditsUnauthorized(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, diff --git a/svc/api/routes/v2_keys_update_credits/403_test.go b/svc/api/routes/v2_keys_update_credits/403_test.go index 5245a6dd0c..6b2652b9ff 100644 --- a/svc/api/routes/v2_keys_update_credits/403_test.go +++ b/svc/api/routes/v2_keys_update_credits/403_test.go @@ -20,7 +20,6 @@ func TestKeyUpdateCreditsForbidden(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, diff --git a/svc/api/routes/v2_keys_update_credits/404_test.go b/svc/api/routes/v2_keys_update_credits/404_test.go index 9f3b0a563c..b096093f0c 100644 --- a/svc/api/routes/v2_keys_update_credits/404_test.go +++ b/svc/api/routes/v2_keys_update_credits/404_test.go @@ -18,7 +18,6 @@ func TestUpdateKeyCreditsNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, diff --git a/svc/api/routes/v2_keys_update_credits/BUILD.bazel b/svc/api/routes/v2_keys_update_credits/BUILD.bazel index 909e522d03..2e798508d8 100644 --- a/svc/api/routes/v2_keys_update_credits/BUILD.bazel +++ b/svc/api/routes/v2_keys_update_credits/BUILD.bazel @@ -14,7 +14,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_keys_update_credits/handler.go b/svc/api/routes/v2_keys_update_credits/handler.go index 06792a07dd..83311d98e9 100644 --- a/svc/api/routes/v2_keys_update_credits/handler.go +++ b/svc/api/routes/v2_keys_update_credits/handler.go @@ -15,7 +15,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -26,7 +26,6 @@ type Response = openapi.V2KeysUpdateCreditsResponseBody // Handler implements zen.Route interface for the v2 keys.updateCredits endpoint type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -45,8 +44,6 @@ func (h *Handler) Path() string { } func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/keys.updateCredits") - // Authentication auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() @@ -267,7 +264,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { h.KeyCache.Remove(ctx, key.Hash) if err := h.UsageLimiter.Invalidate(ctx, key.ID); err != nil { - h.Logger.Error("Failed to invalidate usage limit", + logger.Error("Failed to invalidate usage limit", "error", err.Error(), "key_id", key.ID, ) diff --git a/svc/api/routes/v2_keys_update_key/200_test.go b/svc/api/routes/v2_keys_update_key/200_test.go index 63580d9d8b..3b0cebab14 100644 --- a/svc/api/routes/v2_keys_update_key/200_test.go +++ b/svc/api/routes/v2_keys_update_key/200_test.go @@ -31,7 +31,6 @@ func TestUpdateKeySuccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, @@ -135,7 +134,6 @@ func TestUpdateKeyUpdateAllFields(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, @@ -210,7 +208,6 @@ func TestKeyUpdateCreditsInvalidatesCache(t *testing.T) { ctx := context.Background() route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, @@ -293,7 +290,6 @@ func TestUpdateKeyConcurrentWithSameExternalId(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, @@ -380,7 +376,6 @@ func TestUpdateKeyConcurrentRatelimits(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, diff --git a/svc/api/routes/v2_keys_update_key/400_test.go b/svc/api/routes/v2_keys_update_key/400_test.go index def47d511f..d77b0eedd5 100644 --- a/svc/api/routes/v2_keys_update_key/400_test.go +++ b/svc/api/routes/v2_keys_update_key/400_test.go @@ -22,7 +22,6 @@ func TestUpdateKeyInvalidRefillConfig(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, diff --git a/svc/api/routes/v2_keys_update_key/401_test.go b/svc/api/routes/v2_keys_update_key/401_test.go index 11695b5cf5..c44ce85426 100644 --- a/svc/api/routes/v2_keys_update_key/401_test.go +++ b/svc/api/routes/v2_keys_update_key/401_test.go @@ -20,7 +20,6 @@ func TestUpdateKeyUnauthorized(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, diff --git a/svc/api/routes/v2_keys_update_key/403_test.go b/svc/api/routes/v2_keys_update_key/403_test.go index 5074d6356a..9367e31725 100644 --- a/svc/api/routes/v2_keys_update_key/403_test.go +++ b/svc/api/routes/v2_keys_update_key/403_test.go @@ -38,7 +38,6 @@ func TestUpdateKeyCorrectPermissions(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, @@ -91,7 +90,6 @@ func TestUpdateKeyInsufficientPermissions(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, @@ -137,7 +135,6 @@ func TestUpdateKeyCrossWorkspaceIsolation(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, diff --git a/svc/api/routes/v2_keys_update_key/404_test.go b/svc/api/routes/v2_keys_update_key/404_test.go index 0339fc1630..8ed188df24 100644 --- a/svc/api/routes/v2_keys_update_key/404_test.go +++ b/svc/api/routes/v2_keys_update_key/404_test.go @@ -21,7 +21,6 @@ func TestUpdateKeyNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, diff --git a/svc/api/routes/v2_keys_update_key/BUILD.bazel b/svc/api/routes/v2_keys_update_key/BUILD.bazel index 5bab2d8823..acb004fd5b 100644 --- a/svc/api/routes/v2_keys_update_key/BUILD.bazel +++ b/svc/api/routes/v2_keys_update_key/BUILD.bazel @@ -15,7 +15,7 @@ go_library( "//pkg/db", "//pkg/db/types", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/rbac", "//pkg/uid", "//pkg/zen", diff --git a/svc/api/routes/v2_keys_update_key/handler.go b/svc/api/routes/v2_keys_update_key/handler.go index 313b7d699b..afb6e892e0 100644 --- a/svc/api/routes/v2_keys_update_key/handler.go +++ b/svc/api/routes/v2_keys_update_key/handler.go @@ -19,7 +19,7 @@ import ( "github.com/unkeyed/unkey/pkg/db" dbtype "github.com/unkeyed/unkey/pkg/db/types" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/pkg/zen" @@ -31,7 +31,6 @@ type ( ) type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -51,8 +50,6 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/keys.updateKey") - auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() if err != nil { @@ -597,7 +594,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { h.KeyCache.Remove(ctx, key.Hash) if req.Credits.IsSpecified() { if err := h.UsageLimiter.Invalidate(ctx, key.ID); err != nil { - h.Logger.Error("Failed to invalidate usage limit", + logger.Error("Failed to invalidate usage limit", "error", err.Error(), "key_id", key.ID, ) diff --git a/svc/api/routes/v2_keys_update_key/three_state_test.go b/svc/api/routes/v2_keys_update_key/three_state_test.go index 7ca9ab648b..5ac0365d59 100644 --- a/svc/api/routes/v2_keys_update_key/three_state_test.go +++ b/svc/api/routes/v2_keys_update_key/three_state_test.go @@ -30,7 +30,6 @@ func TestThreeStateUpdateLogic(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, KeyCache: h.Caches.VerificationKeyByHash, UsageLimiter: h.UsageLimiter, diff --git a/svc/api/routes/v2_keys_verify_key/200_test.go b/svc/api/routes/v2_keys_verify_key/200_test.go index 6e3d86509b..bf3fdd9b2c 100644 --- a/svc/api/routes/v2_keys_verify_key/200_test.go +++ b/svc/api/routes/v2_keys_verify_key/200_test.go @@ -23,7 +23,6 @@ func TestSuccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ClickHouse: h.ClickHouse, } diff --git a/svc/api/routes/v2_keys_verify_key/400_test.go b/svc/api/routes/v2_keys_verify_key/400_test.go index 1cf3a8fcd7..e2576c887c 100644 --- a/svc/api/routes/v2_keys_verify_key/400_test.go +++ b/svc/api/routes/v2_keys_verify_key/400_test.go @@ -19,7 +19,6 @@ func TestBadRequest(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ClickHouse: h.ClickHouse, } diff --git a/svc/api/routes/v2_keys_verify_key/401_test.go b/svc/api/routes/v2_keys_verify_key/401_test.go index 7e8e139d8e..76b18465eb 100644 --- a/svc/api/routes/v2_keys_verify_key/401_test.go +++ b/svc/api/routes/v2_keys_verify_key/401_test.go @@ -17,7 +17,6 @@ func TestUnauthorized(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ClickHouse: h.ClickHouse, } diff --git a/svc/api/routes/v2_keys_verify_key/403_test.go b/svc/api/routes/v2_keys_verify_key/403_test.go index 357fa0d216..1bc3e60777 100644 --- a/svc/api/routes/v2_keys_verify_key/403_test.go +++ b/svc/api/routes/v2_keys_verify_key/403_test.go @@ -18,7 +18,6 @@ func TestForbidden_NoVerifyPermissions(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ClickHouse: h.ClickHouse, } diff --git a/svc/api/routes/v2_keys_verify_key/404_test.go b/svc/api/routes/v2_keys_verify_key/404_test.go index 142ed025b8..3d28c0f56d 100644 --- a/svc/api/routes/v2_keys_verify_key/404_test.go +++ b/svc/api/routes/v2_keys_verify_key/404_test.go @@ -19,7 +19,6 @@ func TestNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ClickHouse: h.ClickHouse, } diff --git a/svc/api/routes/v2_keys_verify_key/412_test.go b/svc/api/routes/v2_keys_verify_key/412_test.go index 8a86d0bbf2..3175613559 100644 --- a/svc/api/routes/v2_keys_verify_key/412_test.go +++ b/svc/api/routes/v2_keys_verify_key/412_test.go @@ -19,7 +19,6 @@ func TestPreconditionFailed(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ClickHouse: h.ClickHouse, } diff --git a/svc/api/routes/v2_keys_verify_key/BUILD.bazel b/svc/api/routes/v2_keys_verify_key/BUILD.bazel index 3d41e6eec8..5088fc3951 100644 --- a/svc/api/routes/v2_keys_verify_key/BUILD.bazel +++ b/svc/api/routes/v2_keys_verify_key/BUILD.bazel @@ -13,7 +13,7 @@ go_library( "//pkg/db", "//pkg/fault", "//pkg/hash", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/ptr", "//pkg/rbac", "//pkg/zen", diff --git a/svc/api/routes/v2_keys_verify_key/handler.go b/svc/api/routes/v2_keys_verify_key/handler.go index 16e9982a5c..c8682e0a31 100644 --- a/svc/api/routes/v2_keys_verify_key/handler.go +++ b/svc/api/routes/v2_keys_verify_key/handler.go @@ -15,7 +15,7 @@ import ( "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" "github.com/unkeyed/unkey/pkg/hash" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" @@ -30,7 +30,6 @@ const DefaultCost = 1 // Handler implements zen.Route interface for the v2 keys.verify endpoint type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -48,8 +47,6 @@ func (h *Handler) Path() string { } func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/keys.verifyKey") - // Authentication auth, rootEmit, err := h.Keys.GetRootKey(ctx, s) defer rootEmit() @@ -212,7 +209,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { if key.Key.Meta.Valid { meta, err := db.UnmarshalNullableJSONTo[map[string]any](key.Key.Meta.String) if err != nil { - h.Logger.Error("failed to unmarshal key meta", "keyId", key.Key.ID, "error", err) + logger.Error("failed to unmarshal key meta", "keyId", key.Key.ID, "error", err) } keyData.Meta = meta } @@ -246,7 +243,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { meta, err := db.UnmarshalNullableJSONTo[map[string]any](key.Key.IdentityMeta) if err != nil { - h.Logger.Error( + logger.Error( "failed to unmarshal identity meta", "identityId", key.Key.IdentityID.String, "error", err, diff --git a/svc/api/routes/v2_keys_verify_key/migration_test.go b/svc/api/routes/v2_keys_verify_key/migration_test.go index 05a93e95ab..59dee5a4f1 100644 --- a/svc/api/routes/v2_keys_verify_key/migration_test.go +++ b/svc/api/routes/v2_keys_verify_key/migration_test.go @@ -24,7 +24,6 @@ func TestKeyVerificationWithMigration(t *testing.T) { h := testutil.NewHarness(t) migrateRoute := &migrateHandler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, @@ -34,7 +33,6 @@ func TestKeyVerificationWithMigration(t *testing.T) { verifyRoute := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ClickHouse: h.ClickHouse, } diff --git a/svc/api/routes/v2_keys_verify_key/multilimit_test.go b/svc/api/routes/v2_keys_verify_key/multilimit_test.go index 67aac54ed5..9a8ca1e0a6 100644 --- a/svc/api/routes/v2_keys_verify_key/multilimit_test.go +++ b/svc/api/routes/v2_keys_verify_key/multilimit_test.go @@ -19,7 +19,6 @@ func TestMultiLimit(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ClickHouse: h.ClickHouse, } diff --git a/svc/api/routes/v2_keys_verify_key/multiple_ratelimits_overcommit_test.go b/svc/api/routes/v2_keys_verify_key/multiple_ratelimits_overcommit_test.go index bbfc064dd7..8ed96f117a 100644 --- a/svc/api/routes/v2_keys_verify_key/multiple_ratelimits_overcommit_test.go +++ b/svc/api/routes/v2_keys_verify_key/multiple_ratelimits_overcommit_test.go @@ -34,7 +34,6 @@ func TestMultipleRatelimitsCounterLeakBug(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ClickHouse: h.ClickHouse, } diff --git a/svc/api/routes/v2_keys_verify_key/ratelimit_response_test.go b/svc/api/routes/v2_keys_verify_key/ratelimit_response_test.go index 3c1bb467d9..f1c84361ee 100644 --- a/svc/api/routes/v2_keys_verify_key/ratelimit_response_test.go +++ b/svc/api/routes/v2_keys_verify_key/ratelimit_response_test.go @@ -20,7 +20,6 @@ func TestRatelimitResponse(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ClickHouse: h.ClickHouse, } diff --git a/svc/api/routes/v2_keys_verify_key/resend_demo_test.go b/svc/api/routes/v2_keys_verify_key/resend_demo_test.go index d3361b52b8..7dffb812b6 100644 --- a/svc/api/routes/v2_keys_verify_key/resend_demo_test.go +++ b/svc/api/routes/v2_keys_verify_key/resend_demo_test.go @@ -25,7 +25,6 @@ func TestResendDemo(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, ClickHouse: h.ClickHouse, } diff --git a/svc/api/routes/v2_keys_whoami/200_test.go b/svc/api/routes/v2_keys_whoami/200_test.go index f6616109ef..e654f3301d 100644 --- a/svc/api/routes/v2_keys_whoami/200_test.go +++ b/svc/api/routes/v2_keys_whoami/200_test.go @@ -25,7 +25,6 @@ func TestGetKeyByKey(t *testing.T) { ctx := context.Background() route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, @@ -109,7 +108,6 @@ func TestGetKeyByKey(t *testing.T) { func TestGetKey_AdditionalScenarios(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_whoami/400_test.go b/svc/api/routes/v2_keys_whoami/400_test.go index 14ab46a571..693856f675 100644 --- a/svc/api/routes/v2_keys_whoami/400_test.go +++ b/svc/api/routes/v2_keys_whoami/400_test.go @@ -17,7 +17,6 @@ func TestGetKeyBadRequest(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_whoami/401_test.go b/svc/api/routes/v2_keys_whoami/401_test.go index 344b218ea5..4f8f8a3588 100644 --- a/svc/api/routes/v2_keys_whoami/401_test.go +++ b/svc/api/routes/v2_keys_whoami/401_test.go @@ -17,7 +17,6 @@ func TestGetKeyUnauthorized(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_whoami/404_test.go b/svc/api/routes/v2_keys_whoami/404_test.go index ae9b8d92e6..487aac8c85 100644 --- a/svc/api/routes/v2_keys_whoami/404_test.go +++ b/svc/api/routes/v2_keys_whoami/404_test.go @@ -23,7 +23,6 @@ func TestGetKeyNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } @@ -58,7 +57,6 @@ func TestGetKeyForbidden(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, Vault: h.Vault, } diff --git a/svc/api/routes/v2_keys_whoami/500_test.go b/svc/api/routes/v2_keys_whoami/500_test.go index fa86174b9b..073b7134c4 100644 --- a/svc/api/routes/v2_keys_whoami/500_test.go +++ b/svc/api/routes/v2_keys_whoami/500_test.go @@ -14,7 +14,6 @@ import ( func TestInternalError(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - Logger: h.Logger, DB: h.DB, Keys: h.Keys, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_keys_whoami/BUILD.bazel b/svc/api/routes/v2_keys_whoami/BUILD.bazel index 024a0f5ee8..19f52a5711 100644 --- a/svc/api/routes/v2_keys_whoami/BUILD.bazel +++ b/svc/api/routes/v2_keys_whoami/BUILD.bazel @@ -12,7 +12,7 @@ go_library( "//pkg/db", "//pkg/fault", "//pkg/hash", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/rbac", "//pkg/vault", "//pkg/zen", diff --git a/svc/api/routes/v2_keys_whoami/handler.go b/svc/api/routes/v2_keys_whoami/handler.go index 61a2ceac21..8d2809a960 100644 --- a/svc/api/routes/v2_keys_whoami/handler.go +++ b/svc/api/routes/v2_keys_whoami/handler.go @@ -12,7 +12,7 @@ import ( "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" "github.com/unkeyed/unkey/pkg/hash" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/vault" "github.com/unkeyed/unkey/pkg/zen" @@ -26,7 +26,6 @@ type ( // Handler implements zen.Route interface for the v2 keys.whoami endpoint type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -162,7 +161,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { response.Identity.Meta = identityMeta if err != nil { - h.Logger.Error("failed to unmarshal identity meta", "error", err) + logger.Error("failed to unmarshal identity meta", "error", err) } } } @@ -219,7 +218,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { // Set meta meta, err := db.UnmarshalNullableJSONTo[map[string]any](keyData.Key.Meta.String) if err != nil { - h.Logger.Error("failed to unmarshal key meta", "error", err) + logger.Error("failed to unmarshal key meta", "error", err) } response.Meta = meta diff --git a/svc/api/routes/v2_permissions_create_permission/200_test.go b/svc/api/routes/v2_permissions_create_permission/200_test.go index 1ddaae908d..f61296e67f 100644 --- a/svc/api/routes/v2_permissions_create_permission/200_test.go +++ b/svc/api/routes/v2_permissions_create_permission/200_test.go @@ -19,7 +19,6 @@ func TestSuccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_create_permission/400_test.go b/svc/api/routes/v2_permissions_create_permission/400_test.go index 854ff9d18f..b33274b61b 100644 --- a/svc/api/routes/v2_permissions_create_permission/400_test.go +++ b/svc/api/routes/v2_permissions_create_permission/400_test.go @@ -18,7 +18,6 @@ func TestValidationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_create_permission/401_test.go b/svc/api/routes/v2_permissions_create_permission/401_test.go index 3b143b6a21..31826ad420 100644 --- a/svc/api/routes/v2_permissions_create_permission/401_test.go +++ b/svc/api/routes/v2_permissions_create_permission/401_test.go @@ -16,7 +16,6 @@ func TestAuthenticationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_create_permission/403_test.go b/svc/api/routes/v2_permissions_create_permission/403_test.go index af9b234439..4261cd6bb9 100644 --- a/svc/api/routes/v2_permissions_create_permission/403_test.go +++ b/svc/api/routes/v2_permissions_create_permission/403_test.go @@ -17,7 +17,6 @@ func TestAuthorizationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_create_permission/409_test.go b/svc/api/routes/v2_permissions_create_permission/409_test.go index 9884baf9f4..bf66f197f8 100644 --- a/svc/api/routes/v2_permissions_create_permission/409_test.go +++ b/svc/api/routes/v2_permissions_create_permission/409_test.go @@ -17,7 +17,6 @@ func TestConflictErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_create_permission/BUILD.bazel b/svc/api/routes/v2_permissions_create_permission/BUILD.bazel index e16d8f789a..06572bb4e7 100644 --- a/svc/api/routes/v2_permissions_create_permission/BUILD.bazel +++ b/svc/api/routes/v2_permissions_create_permission/BUILD.bazel @@ -13,7 +13,6 @@ go_library( "//pkg/db", "//pkg/db/types", "//pkg/fault", - "//pkg/otel/logging", "//pkg/ptr", "//pkg/rbac", "//pkg/uid", diff --git a/svc/api/routes/v2_permissions_create_permission/handler.go b/svc/api/routes/v2_permissions_create_permission/handler.go index 15f644754a..6b38ad88e9 100644 --- a/svc/api/routes/v2_permissions_create_permission/handler.go +++ b/svc/api/routes/v2_permissions_create_permission/handler.go @@ -13,7 +13,6 @@ import ( "github.com/unkeyed/unkey/pkg/db" dbtype "github.com/unkeyed/unkey/pkg/db/types" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" @@ -26,8 +25,6 @@ type Response = openapi.V2PermissionsCreatePermissionResponseBody // Handler implements zen.Route interface for the v2 permissions create permission endpoint type Handler struct { - // Services as public fields - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService diff --git a/svc/api/routes/v2_permissions_create_role/200_test.go b/svc/api/routes/v2_permissions_create_role/200_test.go index 3a34cf43cb..a4e42d3c77 100644 --- a/svc/api/routes/v2_permissions_create_role/200_test.go +++ b/svc/api/routes/v2_permissions_create_role/200_test.go @@ -19,7 +19,6 @@ func TestSuccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_create_role/400_test.go b/svc/api/routes/v2_permissions_create_role/400_test.go index 577c228473..ed69715971 100644 --- a/svc/api/routes/v2_permissions_create_role/400_test.go +++ b/svc/api/routes/v2_permissions_create_role/400_test.go @@ -18,7 +18,6 @@ func TestValidationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_create_role/401_test.go b/svc/api/routes/v2_permissions_create_role/401_test.go index a63678d8f4..e4226c2b5a 100644 --- a/svc/api/routes/v2_permissions_create_role/401_test.go +++ b/svc/api/routes/v2_permissions_create_role/401_test.go @@ -16,7 +16,6 @@ func TestAuthenticationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_create_role/403_test.go b/svc/api/routes/v2_permissions_create_role/403_test.go index e2eafe3a58..211216c27b 100644 --- a/svc/api/routes/v2_permissions_create_role/403_test.go +++ b/svc/api/routes/v2_permissions_create_role/403_test.go @@ -19,7 +19,6 @@ func TestAuthorizationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_create_role/409_test.go b/svc/api/routes/v2_permissions_create_role/409_test.go index 7df9a68240..99a168c637 100644 --- a/svc/api/routes/v2_permissions_create_role/409_test.go +++ b/svc/api/routes/v2_permissions_create_role/409_test.go @@ -21,7 +21,6 @@ func TestConflictErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_create_role/BUILD.bazel b/svc/api/routes/v2_permissions_create_role/BUILD.bazel index 16ca740db6..6c940977df 100644 --- a/svc/api/routes/v2_permissions_create_role/BUILD.bazel +++ b/svc/api/routes/v2_permissions_create_role/BUILD.bazel @@ -12,7 +12,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/ptr", "//pkg/rbac", "//pkg/uid", diff --git a/svc/api/routes/v2_permissions_create_role/handler.go b/svc/api/routes/v2_permissions_create_role/handler.go index 2708e8513e..fc8252dacd 100644 --- a/svc/api/routes/v2_permissions_create_role/handler.go +++ b/svc/api/routes/v2_permissions_create_role/handler.go @@ -13,7 +13,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" @@ -26,8 +26,6 @@ type Response = openapi.V2PermissionsCreateRoleResponseBody // Handler implements zen.Route interface for the v2 permissions create role endpoint type Handler struct { - // Services as public fields - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -45,7 +43,7 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/permissions.createRole") + logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/permissions.createRole") // 1. Authentication auth, emit, err := h.Keys.GetRootKey(ctx, s) diff --git a/svc/api/routes/v2_permissions_delete_permission/200_test.go b/svc/api/routes/v2_permissions_delete_permission/200_test.go index 6d2a6ecea9..00027a9525 100644 --- a/svc/api/routes/v2_permissions_delete_permission/200_test.go +++ b/svc/api/routes/v2_permissions_delete_permission/200_test.go @@ -22,7 +22,6 @@ func TestSuccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_delete_permission/400_test.go b/svc/api/routes/v2_permissions_delete_permission/400_test.go index 27cd78675b..1a662b4b26 100644 --- a/svc/api/routes/v2_permissions_delete_permission/400_test.go +++ b/svc/api/routes/v2_permissions_delete_permission/400_test.go @@ -17,7 +17,6 @@ func TestValidationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_delete_permission/401_test.go b/svc/api/routes/v2_permissions_delete_permission/401_test.go index 04eafd78c4..37472f013a 100644 --- a/svc/api/routes/v2_permissions_delete_permission/401_test.go +++ b/svc/api/routes/v2_permissions_delete_permission/401_test.go @@ -16,7 +16,6 @@ func TestAuthenticationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_delete_permission/403_test.go b/svc/api/routes/v2_permissions_delete_permission/403_test.go index 90c29b47e4..50f532128b 100644 --- a/svc/api/routes/v2_permissions_delete_permission/403_test.go +++ b/svc/api/routes/v2_permissions_delete_permission/403_test.go @@ -23,7 +23,6 @@ func TestAuthorizationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_delete_permission/404_test.go b/svc/api/routes/v2_permissions_delete_permission/404_test.go index 13ac489b51..6c682f5797 100644 --- a/svc/api/routes/v2_permissions_delete_permission/404_test.go +++ b/svc/api/routes/v2_permissions_delete_permission/404_test.go @@ -23,7 +23,6 @@ func TestNotFoundErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_delete_permission/BUILD.bazel b/svc/api/routes/v2_permissions_delete_permission/BUILD.bazel index b376b6f9d1..48a08ff732 100644 --- a/svc/api/routes/v2_permissions_delete_permission/BUILD.bazel +++ b/svc/api/routes/v2_permissions_delete_permission/BUILD.bazel @@ -12,7 +12,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_permissions_delete_permission/handler.go b/svc/api/routes/v2_permissions_delete_permission/handler.go index 05f1304802..bd4459d8f7 100644 --- a/svc/api/routes/v2_permissions_delete_permission/handler.go +++ b/svc/api/routes/v2_permissions_delete_permission/handler.go @@ -10,7 +10,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -21,8 +20,6 @@ type Response = openapi.V2PermissionsDeletePermissionResponseBody // Handler implements zen.Route interface for the v2 permissions delete permission endpoint type Handler struct { - // Services as public fields - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService diff --git a/svc/api/routes/v2_permissions_delete_role/200_test.go b/svc/api/routes/v2_permissions_delete_role/200_test.go index d6a79c705b..772ab5d6e5 100644 --- a/svc/api/routes/v2_permissions_delete_role/200_test.go +++ b/svc/api/routes/v2_permissions_delete_role/200_test.go @@ -24,7 +24,6 @@ func TestSuccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_delete_role/400_test.go b/svc/api/routes/v2_permissions_delete_role/400_test.go index fefb5ac93f..797b931141 100644 --- a/svc/api/routes/v2_permissions_delete_role/400_test.go +++ b/svc/api/routes/v2_permissions_delete_role/400_test.go @@ -17,7 +17,6 @@ func TestValidationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_delete_role/401_test.go b/svc/api/routes/v2_permissions_delete_role/401_test.go index 7afe44aa9a..7ec9081313 100644 --- a/svc/api/routes/v2_permissions_delete_role/401_test.go +++ b/svc/api/routes/v2_permissions_delete_role/401_test.go @@ -16,7 +16,6 @@ func TestAuthenticationErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_delete_role/403_test.go b/svc/api/routes/v2_permissions_delete_role/403_test.go index be12cf565a..16101584e3 100644 --- a/svc/api/routes/v2_permissions_delete_role/403_test.go +++ b/svc/api/routes/v2_permissions_delete_role/403_test.go @@ -22,7 +22,6 @@ func TestPermissionErrors(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_delete_role/404_test.go b/svc/api/routes/v2_permissions_delete_role/404_test.go index 95e2dc1141..a97747505e 100644 --- a/svc/api/routes/v2_permissions_delete_role/404_test.go +++ b/svc/api/routes/v2_permissions_delete_role/404_test.go @@ -22,7 +22,6 @@ func TestNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, } diff --git a/svc/api/routes/v2_permissions_delete_role/BUILD.bazel b/svc/api/routes/v2_permissions_delete_role/BUILD.bazel index f9e341881f..b7bac56b40 100644 --- a/svc/api/routes/v2_permissions_delete_role/BUILD.bazel +++ b/svc/api/routes/v2_permissions_delete_role/BUILD.bazel @@ -12,7 +12,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_permissions_delete_role/handler.go b/svc/api/routes/v2_permissions_delete_role/handler.go index ab6f1ba35b..e2bcb7d482 100644 --- a/svc/api/routes/v2_permissions_delete_role/handler.go +++ b/svc/api/routes/v2_permissions_delete_role/handler.go @@ -10,7 +10,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -21,8 +21,6 @@ type Response = openapi.V2PermissionsDeleteRoleResponseBody // Handler implements zen.Route interface for the v2 permissions delete role endpoint type Handler struct { - // Services as public fields - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService @@ -40,7 +38,7 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/permissions.deleteRole") + logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/permissions.deleteRole") // 1. Authentication auth, emit, err := h.Keys.GetRootKey(ctx, s) diff --git a/svc/api/routes/v2_permissions_get_permission/200_test.go b/svc/api/routes/v2_permissions_get_permission/200_test.go index 547d5d2fdc..889596499d 100644 --- a/svc/api/routes/v2_permissions_get_permission/200_test.go +++ b/svc/api/routes/v2_permissions_get_permission/200_test.go @@ -20,9 +20,8 @@ func TestSuccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_get_permission/400_test.go b/svc/api/routes/v2_permissions_get_permission/400_test.go index 48bf855f68..15e9504b91 100644 --- a/svc/api/routes/v2_permissions_get_permission/400_test.go +++ b/svc/api/routes/v2_permissions_get_permission/400_test.go @@ -15,9 +15,8 @@ func TestValidationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_get_permission/401_test.go b/svc/api/routes/v2_permissions_get_permission/401_test.go index f1652d8ca6..d019fad66d 100644 --- a/svc/api/routes/v2_permissions_get_permission/401_test.go +++ b/svc/api/routes/v2_permissions_get_permission/401_test.go @@ -14,9 +14,8 @@ func TestAuthenticationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_get_permission/403_test.go b/svc/api/routes/v2_permissions_get_permission/403_test.go index 4e68abdbd2..32c8269218 100644 --- a/svc/api/routes/v2_permissions_get_permission/403_test.go +++ b/svc/api/routes/v2_permissions_get_permission/403_test.go @@ -21,9 +21,8 @@ func TestPermissionErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_get_permission/404_test.go b/svc/api/routes/v2_permissions_get_permission/404_test.go index b89ace5738..d130fbe9e9 100644 --- a/svc/api/routes/v2_permissions_get_permission/404_test.go +++ b/svc/api/routes/v2_permissions_get_permission/404_test.go @@ -16,9 +16,8 @@ func TestNotFoundErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_get_permission/BUILD.bazel b/svc/api/routes/v2_permissions_get_permission/BUILD.bazel index 5e487bcb82..a0fad09676 100644 --- a/svc/api/routes/v2_permissions_get_permission/BUILD.bazel +++ b/svc/api/routes/v2_permissions_get_permission/BUILD.bazel @@ -10,7 +10,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_permissions_get_permission/handler.go b/svc/api/routes/v2_permissions_get_permission/handler.go index 4929b68f31..81f80d2651 100644 --- a/svc/api/routes/v2_permissions_get_permission/handler.go +++ b/svc/api/routes/v2_permissions_get_permission/handler.go @@ -8,7 +8,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -19,10 +18,8 @@ type Response = openapi.V2PermissionsGetPermissionResponseBody // Handler implements zen.Route interface for the v2 permissions get permission endpoint type Handler struct { - // Services as public fields - Logger logging.Logger - DB db.Database - Keys keys.KeyService + DB db.Database + Keys keys.KeyService } // Method returns the HTTP method this route responds to @@ -37,7 +34,6 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/permissions.getPermission") // 1. Authentication auth, emit, err := h.Keys.GetRootKey(ctx, s) diff --git a/svc/api/routes/v2_permissions_get_role/200_test.go b/svc/api/routes/v2_permissions_get_role/200_test.go index 080e2bc525..ea9f491794 100644 --- a/svc/api/routes/v2_permissions_get_role/200_test.go +++ b/svc/api/routes/v2_permissions_get_role/200_test.go @@ -21,9 +21,8 @@ func TestSuccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_get_role/400_test.go b/svc/api/routes/v2_permissions_get_role/400_test.go index fcddf7fb4e..aad59acd94 100644 --- a/svc/api/routes/v2_permissions_get_role/400_test.go +++ b/svc/api/routes/v2_permissions_get_role/400_test.go @@ -15,9 +15,8 @@ func TestValidationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_get_role/401_test.go b/svc/api/routes/v2_permissions_get_role/401_test.go index e20f1c10b4..e38131f6ae 100644 --- a/svc/api/routes/v2_permissions_get_role/401_test.go +++ b/svc/api/routes/v2_permissions_get_role/401_test.go @@ -14,9 +14,8 @@ func TestAuthenticationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_get_role/403_test.go b/svc/api/routes/v2_permissions_get_role/403_test.go index 09914c1c60..ddc84e91ac 100644 --- a/svc/api/routes/v2_permissions_get_role/403_test.go +++ b/svc/api/routes/v2_permissions_get_role/403_test.go @@ -20,9 +20,8 @@ func TestPermissionErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_get_role/404_test.go b/svc/api/routes/v2_permissions_get_role/404_test.go index 9de47d0034..b971ea97eb 100644 --- a/svc/api/routes/v2_permissions_get_role/404_test.go +++ b/svc/api/routes/v2_permissions_get_role/404_test.go @@ -15,9 +15,8 @@ func TestNotFoundErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_get_role/BUILD.bazel b/svc/api/routes/v2_permissions_get_role/BUILD.bazel index 58a7f43c0b..1cd6a8e498 100644 --- a/svc/api/routes/v2_permissions_get_role/BUILD.bazel +++ b/svc/api/routes/v2_permissions_get_role/BUILD.bazel @@ -10,7 +10,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_permissions_get_role/handler.go b/svc/api/routes/v2_permissions_get_role/handler.go index 7aa2923cb1..b6f031f872 100644 --- a/svc/api/routes/v2_permissions_get_role/handler.go +++ b/svc/api/routes/v2_permissions_get_role/handler.go @@ -8,7 +8,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -21,10 +21,8 @@ type ( // Handler implements zen.Route interface for the v2 permissions get role endpoint type Handler struct { - // Services as public fields - Logger logging.Logger - DB db.Database - Keys keys.KeyService + DB db.Database + Keys keys.KeyService } // Method returns the HTTP method this route responds to @@ -39,7 +37,7 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/permissions.getRole") + logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/permissions.getRole") // 1. Authentication auth, emit, err := h.Keys.GetRootKey(ctx, s) @@ -91,7 +89,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { perms, err := db.UnmarshalNullableJSONTo[[]db.Permission](role.Permissions) if err != nil { - h.Logger.Error("Failed to unmarshal permissions", "error", err) + logger.Error("Failed to unmarshal permissions", "error", err) } for _, perm := range perms { diff --git a/svc/api/routes/v2_permissions_list_permissions/200_test.go b/svc/api/routes/v2_permissions_list_permissions/200_test.go index 2a7a6ae7d8..318ee7a07f 100644 --- a/svc/api/routes/v2_permissions_list_permissions/200_test.go +++ b/svc/api/routes/v2_permissions_list_permissions/200_test.go @@ -21,9 +21,8 @@ func TestSuccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_list_permissions/400_test.go b/svc/api/routes/v2_permissions_list_permissions/400_test.go index e9d261e022..e399210eee 100644 --- a/svc/api/routes/v2_permissions_list_permissions/400_test.go +++ b/svc/api/routes/v2_permissions_list_permissions/400_test.go @@ -15,9 +15,8 @@ func TestValidationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_list_permissions/401_test.go b/svc/api/routes/v2_permissions_list_permissions/401_test.go index 057b063f79..8702719ca8 100644 --- a/svc/api/routes/v2_permissions_list_permissions/401_test.go +++ b/svc/api/routes/v2_permissions_list_permissions/401_test.go @@ -14,9 +14,8 @@ func TestAuthenticationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_list_permissions/403_test.go b/svc/api/routes/v2_permissions_list_permissions/403_test.go index a71d10f4e6..0afea9688c 100644 --- a/svc/api/routes/v2_permissions_list_permissions/403_test.go +++ b/svc/api/routes/v2_permissions_list_permissions/403_test.go @@ -21,9 +21,8 @@ func TestAuthorizationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_list_permissions/BUILD.bazel b/svc/api/routes/v2_permissions_list_permissions/BUILD.bazel index 90a9c8af38..43aea2d09b 100644 --- a/svc/api/routes/v2_permissions_list_permissions/BUILD.bazel +++ b/svc/api/routes/v2_permissions_list_permissions/BUILD.bazel @@ -10,7 +10,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/ptr", "//pkg/rbac", "//pkg/zen", diff --git a/svc/api/routes/v2_permissions_list_permissions/handler.go b/svc/api/routes/v2_permissions_list_permissions/handler.go index 2a9be9625b..09e820d2d9 100644 --- a/svc/api/routes/v2_permissions_list_permissions/handler.go +++ b/svc/api/routes/v2_permissions_list_permissions/handler.go @@ -8,7 +8,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" @@ -22,9 +21,8 @@ type ( // Handler implements zen.Route interface for the v2 permissions list permissions endpoint type Handler struct { - Logger logging.Logger - DB db.Database - Keys keys.KeyService + DB db.Database + Keys keys.KeyService } // Method returns the HTTP method this route responds to @@ -39,8 +37,6 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/permissions.listPermissions") - // 1. Authentication auth, emit, err := h.Keys.GetRootKey(ctx, s) defer emit() diff --git a/svc/api/routes/v2_permissions_list_roles/200_test.go b/svc/api/routes/v2_permissions_list_roles/200_test.go index e9b0d8e13a..681477d159 100644 --- a/svc/api/routes/v2_permissions_list_roles/200_test.go +++ b/svc/api/routes/v2_permissions_list_roles/200_test.go @@ -21,9 +21,8 @@ func TestSuccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_list_roles/400_test.go b/svc/api/routes/v2_permissions_list_roles/400_test.go index cb62b0f049..11d64a91da 100644 --- a/svc/api/routes/v2_permissions_list_roles/400_test.go +++ b/svc/api/routes/v2_permissions_list_roles/400_test.go @@ -15,9 +15,8 @@ func TestValidationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_list_roles/401_test.go b/svc/api/routes/v2_permissions_list_roles/401_test.go index 3adefcc4a9..eeb514093e 100644 --- a/svc/api/routes/v2_permissions_list_roles/401_test.go +++ b/svc/api/routes/v2_permissions_list_roles/401_test.go @@ -14,9 +14,8 @@ func TestAuthenticationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_list_roles/403_test.go b/svc/api/routes/v2_permissions_list_roles/403_test.go index f181a843c0..9e6aa7da21 100644 --- a/svc/api/routes/v2_permissions_list_roles/403_test.go +++ b/svc/api/routes/v2_permissions_list_roles/403_test.go @@ -20,9 +20,8 @@ func TestAuthorizationErrors(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_permissions_list_roles/BUILD.bazel b/svc/api/routes/v2_permissions_list_roles/BUILD.bazel index 1757e61656..abeebc9d62 100644 --- a/svc/api/routes/v2_permissions_list_roles/BUILD.bazel +++ b/svc/api/routes/v2_permissions_list_roles/BUILD.bazel @@ -10,7 +10,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/ptr", "//pkg/rbac", "//pkg/zen", diff --git a/svc/api/routes/v2_permissions_list_roles/handler.go b/svc/api/routes/v2_permissions_list_roles/handler.go index 06b16f0cab..8cb3beff3a 100644 --- a/svc/api/routes/v2_permissions_list_roles/handler.go +++ b/svc/api/routes/v2_permissions_list_roles/handler.go @@ -8,7 +8,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" @@ -22,10 +22,8 @@ type ( // Handler implements zen.Route interface for the v2 permissions list roles endpoint type Handler struct { - // Services as public fields - Logger logging.Logger - DB db.Database - Keys keys.KeyService + DB db.Database + Keys keys.KeyService } // Method returns the HTTP method this route responds to @@ -40,7 +38,7 @@ func (h *Handler) Path() string { // Handle processes the HTTP request func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { - h.Logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/permissions.listRoles") + logger.Debug("handling request", "requestId", s.RequestID(), "path", "/v2/permissions.listRoles") // 1. Authentication auth, emit, err := h.Keys.GetRootKey(ctx, s) @@ -103,7 +101,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { perms, err := db.UnmarshalNullableJSONTo[[]db.Permission](role.Permissions) if err != nil { - h.Logger.Error("Failed to unmarshal permissions", "error", err) + logger.Error("Failed to unmarshal permissions", "error", err) } for _, perm := range perms { diff --git a/svc/api/routes/v2_ratelimit_delete_override/200_test.go b/svc/api/routes/v2_ratelimit_delete_override/200_test.go index f2c1b48850..495bc97fdb 100644 --- a/svc/api/routes/v2_ratelimit_delete_override/200_test.go +++ b/svc/api/routes/v2_ratelimit_delete_override/200_test.go @@ -46,7 +46,6 @@ func TestDeleteOverrideSuccessfully(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_delete_override/400_test.go b/svc/api/routes/v2_ratelimit_delete_override/400_test.go index b54dcc70e0..c7d8553090 100644 --- a/svc/api/routes/v2_ratelimit_delete_override/400_test.go +++ b/svc/api/routes/v2_ratelimit_delete_override/400_test.go @@ -19,7 +19,6 @@ func TestBadRequests(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_delete_override/401_test.go b/svc/api/routes/v2_ratelimit_delete_override/401_test.go index ae8483ea81..72bff81fa1 100644 --- a/svc/api/routes/v2_ratelimit_delete_override/401_test.go +++ b/svc/api/routes/v2_ratelimit_delete_override/401_test.go @@ -16,7 +16,6 @@ func TestUnauthorizedAccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_delete_override/403_test.go b/svc/api/routes/v2_ratelimit_delete_override/403_test.go index 178609d097..81f021ffd1 100644 --- a/svc/api/routes/v2_ratelimit_delete_override/403_test.go +++ b/svc/api/routes/v2_ratelimit_delete_override/403_test.go @@ -46,7 +46,6 @@ func TestWorkspacePermissions(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_delete_override/404_test.go b/svc/api/routes/v2_ratelimit_delete_override/404_test.go index be66139952..9f7ae56451 100644 --- a/svc/api/routes/v2_ratelimit_delete_override/404_test.go +++ b/svc/api/routes/v2_ratelimit_delete_override/404_test.go @@ -32,7 +32,6 @@ func TestNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_delete_override/BUILD.bazel b/svc/api/routes/v2_ratelimit_delete_override/BUILD.bazel index bb7ea5381f..dbdfff1873 100644 --- a/svc/api/routes/v2_ratelimit_delete_override/BUILD.bazel +++ b/svc/api/routes/v2_ratelimit_delete_override/BUILD.bazel @@ -14,7 +14,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_ratelimit_delete_override/handler.go b/svc/api/routes/v2_ratelimit_delete_override/handler.go index fb03d5db4c..a2a5ce1e36 100644 --- a/svc/api/routes/v2_ratelimit_delete_override/handler.go +++ b/svc/api/routes/v2_ratelimit_delete_override/handler.go @@ -17,7 +17,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -29,7 +28,6 @@ type ( ) type Handler struct { - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService diff --git a/svc/api/routes/v2_ratelimit_get_override/200_test.go b/svc/api/routes/v2_ratelimit_get_override/200_test.go index c42afe8c97..810adc7cf3 100644 --- a/svc/api/routes/v2_ratelimit_get_override/200_test.go +++ b/svc/api/routes/v2_ratelimit_get_override/200_test.go @@ -49,7 +49,6 @@ func TestGetOverrideSuccessfully(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_get_override/400_test.go b/svc/api/routes/v2_ratelimit_get_override/400_test.go index c8d616fb26..497027ce61 100644 --- a/svc/api/routes/v2_ratelimit_get_override/400_test.go +++ b/svc/api/routes/v2_ratelimit_get_override/400_test.go @@ -20,7 +20,6 @@ func TestBadRequests(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_get_override/401_test.go b/svc/api/routes/v2_ratelimit_get_override/401_test.go index 4966ee20af..e982911bf3 100644 --- a/svc/api/routes/v2_ratelimit_get_override/401_test.go +++ b/svc/api/routes/v2_ratelimit_get_override/401_test.go @@ -16,7 +16,6 @@ func TestUnauthorizedAccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_get_override/403_test.go b/svc/api/routes/v2_ratelimit_get_override/403_test.go index c74ccff7d8..2c5c83dcf0 100644 --- a/svc/api/routes/v2_ratelimit_get_override/403_test.go +++ b/svc/api/routes/v2_ratelimit_get_override/403_test.go @@ -46,7 +46,6 @@ func TestWorkspacePermissions(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_get_override/404_test.go b/svc/api/routes/v2_ratelimit_get_override/404_test.go index 0d1afad430..dbcbb83447 100644 --- a/svc/api/routes/v2_ratelimit_get_override/404_test.go +++ b/svc/api/routes/v2_ratelimit_get_override/404_test.go @@ -32,7 +32,6 @@ func TestOverrideNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_get_override/BUILD.bazel b/svc/api/routes/v2_ratelimit_get_override/BUILD.bazel index cfca982551..64732dc34a 100644 --- a/svc/api/routes/v2_ratelimit_get_override/BUILD.bazel +++ b/svc/api/routes/v2_ratelimit_get_override/BUILD.bazel @@ -13,7 +13,6 @@ go_library( "//pkg/db", "//pkg/fault", "//pkg/match", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/zen", "//svc/api/openapi", diff --git a/svc/api/routes/v2_ratelimit_get_override/handler.go b/svc/api/routes/v2_ratelimit_get_override/handler.go index 0315a16d25..e06faa597e 100644 --- a/svc/api/routes/v2_ratelimit_get_override/handler.go +++ b/svc/api/routes/v2_ratelimit_get_override/handler.go @@ -13,7 +13,6 @@ import ( "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" "github.com/unkeyed/unkey/pkg/match" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/api/openapi" @@ -26,8 +25,6 @@ type ( // Handler implements zen.Route interface for the v2 ratelimit get override endpoint type Handler struct { - // Services as public fields - Logger logging.Logger DB db.Database Keys keys.KeyService RatelimitNamespaceCache cache.Cache[cache.ScopedKey, db.FindRatelimitNamespace] diff --git a/svc/api/routes/v2_ratelimit_limit/200_test.go b/svc/api/routes/v2_ratelimit_limit/200_test.go index 75be1a778a..02017e78d9 100644 --- a/svc/api/routes/v2_ratelimit_limit/200_test.go +++ b/svc/api/routes/v2_ratelimit_limit/200_test.go @@ -25,7 +25,6 @@ func TestLimitSuccessfully(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, ClickHouse: h.ClickHouse, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, diff --git a/svc/api/routes/v2_ratelimit_limit/400_test.go b/svc/api/routes/v2_ratelimit_limit/400_test.go index cd9ec2a9e1..a8a2784737 100644 --- a/svc/api/routes/v2_ratelimit_limit/400_test.go +++ b/svc/api/routes/v2_ratelimit_limit/400_test.go @@ -22,7 +22,6 @@ func TestBadRequests(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, Auditlogs: h.Auditlogs, @@ -107,7 +106,6 @@ func TestMissingAuthorizationHeader(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_ratelimit_limit/401_test.go b/svc/api/routes/v2_ratelimit_limit/401_test.go index 056b8bc041..ec15a5241e 100644 --- a/svc/api/routes/v2_ratelimit_limit/401_test.go +++ b/svc/api/routes/v2_ratelimit_limit/401_test.go @@ -15,7 +15,6 @@ func TestUnauthorizedAccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_ratelimit_limit/403_test.go b/svc/api/routes/v2_ratelimit_limit/403_test.go index 54888fe0dc..73bad1c4ba 100644 --- a/svc/api/routes/v2_ratelimit_limit/403_test.go +++ b/svc/api/routes/v2_ratelimit_limit/403_test.go @@ -33,7 +33,6 @@ func TestWorkspacePermissions(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, Auditlogs: h.Auditlogs, @@ -72,7 +71,6 @@ func TestInsufficientPermissions(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_ratelimit_limit/410_test.go b/svc/api/routes/v2_ratelimit_limit/410_test.go index 811e0ccfec..e9d0acbb9d 100644 --- a/svc/api/routes/v2_ratelimit_limit/410_test.go +++ b/svc/api/routes/v2_ratelimit_limit/410_test.go @@ -22,7 +22,6 @@ func TestSoftDeletedNamespace(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_ratelimit_limit/BUILD.bazel b/svc/api/routes/v2_ratelimit_limit/BUILD.bazel index 060e7a43f1..dc0b7d4cdf 100644 --- a/svc/api/routes/v2_ratelimit_limit/BUILD.bazel +++ b/svc/api/routes/v2_ratelimit_limit/BUILD.bazel @@ -17,8 +17,8 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", + "//pkg/logger", "//pkg/match", - "//pkg/otel/logging", "//pkg/ptr", "//pkg/rbac", "//pkg/uid", diff --git a/svc/api/routes/v2_ratelimit_limit/accuracy_test.go b/svc/api/routes/v2_ratelimit_limit/accuracy_test.go index 226b2a1201..a8e536a1fa 100644 --- a/svc/api/routes/v2_ratelimit_limit/accuracy_test.go +++ b/svc/api/routes/v2_ratelimit_limit/accuracy_test.go @@ -58,7 +58,6 @@ func TestRateLimitAccuracy(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, ClickHouse: h.ClickHouse, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, diff --git a/svc/api/routes/v2_ratelimit_limit/handler.go b/svc/api/routes/v2_ratelimit_limit/handler.go index 4ba416bf38..7f9ca31b33 100644 --- a/svc/api/routes/v2_ratelimit_limit/handler.go +++ b/svc/api/routes/v2_ratelimit_limit/handler.go @@ -20,8 +20,8 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/match" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" @@ -36,7 +36,6 @@ type ( // Handler implements zen.Route interface for the v2 ratelimit limit endpoint type Handler struct { - Logger logging.Logger Keys keys.KeyService DB db.Database ClickHouse clickhouse.Bufferer @@ -270,7 +269,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { if header != "" { i, parseErr := strconv.ParseInt(header, 10, 64) if parseErr != nil { - h.Logger.Warn("invalid test time", "header", header) + logger.Warn("invalid test time", "header", header) } else { limitReq.Time = time.UnixMilli(i) } diff --git a/svc/api/routes/v2_ratelimit_list_overrides/200_test.go b/svc/api/routes/v2_ratelimit_list_overrides/200_test.go index c3030dbf6a..c155f8ea36 100644 --- a/svc/api/routes/v2_ratelimit_list_overrides/200_test.go +++ b/svc/api/routes/v2_ratelimit_list_overrides/200_test.go @@ -47,9 +47,8 @@ func TestListOverridesSuccessfully(t *testing.T) { require.NoError(t, err) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_ratelimit_list_overrides/400_test.go b/svc/api/routes/v2_ratelimit_list_overrides/400_test.go index b53ae19b5e..2c28347d2d 100644 --- a/svc/api/routes/v2_ratelimit_list_overrides/400_test.go +++ b/svc/api/routes/v2_ratelimit_list_overrides/400_test.go @@ -17,9 +17,8 @@ func TestBadRequests(t *testing.T) { rootKey := h.CreateRootKey(h.Resources().UserWorkspace.ID) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_ratelimit_list_overrides/401_test.go b/svc/api/routes/v2_ratelimit_list_overrides/401_test.go index ebf2d270a5..66d62fcd02 100644 --- a/svc/api/routes/v2_ratelimit_list_overrides/401_test.go +++ b/svc/api/routes/v2_ratelimit_list_overrides/401_test.go @@ -13,9 +13,8 @@ func TestUnauthorizedAccess(t *testing.T) { h := testutil.NewHarness(t) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_ratelimit_list_overrides/403_test.go b/svc/api/routes/v2_ratelimit_list_overrides/403_test.go index f04f89d448..2d246117ac 100644 --- a/svc/api/routes/v2_ratelimit_list_overrides/403_test.go +++ b/svc/api/routes/v2_ratelimit_list_overrides/403_test.go @@ -45,9 +45,8 @@ func TestWorkspacePermissions(t *testing.T) { require.NoError(t, err) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_ratelimit_list_overrides/404_test.go b/svc/api/routes/v2_ratelimit_list_overrides/404_test.go index 941a1256aa..43cf4411bf 100644 --- a/svc/api/routes/v2_ratelimit_list_overrides/404_test.go +++ b/svc/api/routes/v2_ratelimit_list_overrides/404_test.go @@ -31,9 +31,8 @@ func TestOverrideNotFound(t *testing.T) { require.NoError(t, err) route := &handler.Handler{ - DB: h.DB, - Keys: h.Keys, - Logger: h.Logger, + DB: h.DB, + Keys: h.Keys, } h.Register(route) diff --git a/svc/api/routes/v2_ratelimit_list_overrides/BUILD.bazel b/svc/api/routes/v2_ratelimit_list_overrides/BUILD.bazel index 9374b10d96..0a581b6ea6 100644 --- a/svc/api/routes/v2_ratelimit_list_overrides/BUILD.bazel +++ b/svc/api/routes/v2_ratelimit_list_overrides/BUILD.bazel @@ -10,7 +10,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/ptr", "//pkg/rbac", "//pkg/zen", diff --git a/svc/api/routes/v2_ratelimit_list_overrides/handler.go b/svc/api/routes/v2_ratelimit_list_overrides/handler.go index 7cddbd43c0..170c72a6a8 100644 --- a/svc/api/routes/v2_ratelimit_list_overrides/handler.go +++ b/svc/api/routes/v2_ratelimit_list_overrides/handler.go @@ -8,7 +8,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/zen" @@ -22,10 +21,8 @@ type ( // Handler implements zen.Route interface for the v2 ratelimit list overrides endpoint type Handler struct { - // Services as public fields - Logger logging.Logger - DB db.Database - Keys keys.KeyService + DB db.Database + Keys keys.KeyService } // Method returns the HTTP method this route responds to diff --git a/svc/api/routes/v2_ratelimit_multi_limit/200_test.go b/svc/api/routes/v2_ratelimit_multi_limit/200_test.go index 1847160d5e..6da93f434c 100644 --- a/svc/api/routes/v2_ratelimit_multi_limit/200_test.go +++ b/svc/api/routes/v2_ratelimit_multi_limit/200_test.go @@ -25,7 +25,6 @@ func TestLimitSuccessfully(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, ClickHouse: h.ClickHouse, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, diff --git a/svc/api/routes/v2_ratelimit_multi_limit/400_test.go b/svc/api/routes/v2_ratelimit_multi_limit/400_test.go index 61f16dc1c0..137db8d933 100644 --- a/svc/api/routes/v2_ratelimit_multi_limit/400_test.go +++ b/svc/api/routes/v2_ratelimit_multi_limit/400_test.go @@ -22,7 +22,6 @@ func TestBadRequests(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, Auditlogs: h.Auditlogs, @@ -132,7 +131,6 @@ func TestMissingAuthorizationHeader(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_ratelimit_multi_limit/401_test.go b/svc/api/routes/v2_ratelimit_multi_limit/401_test.go index 6978e340b9..de2ba09b99 100644 --- a/svc/api/routes/v2_ratelimit_multi_limit/401_test.go +++ b/svc/api/routes/v2_ratelimit_multi_limit/401_test.go @@ -15,7 +15,6 @@ func TestUnauthorizedAccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_ratelimit_multi_limit/403_test.go b/svc/api/routes/v2_ratelimit_multi_limit/403_test.go index 2719082924..ebb5d9c9dd 100644 --- a/svc/api/routes/v2_ratelimit_multi_limit/403_test.go +++ b/svc/api/routes/v2_ratelimit_multi_limit/403_test.go @@ -33,7 +33,6 @@ func TestWorkspacePermissions(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, Auditlogs: h.Auditlogs, @@ -74,7 +73,6 @@ func TestInsufficientPermissions(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_ratelimit_multi_limit/410_test.go b/svc/api/routes/v2_ratelimit_multi_limit/410_test.go index 6634e176de..b9c9540deb 100644 --- a/svc/api/routes/v2_ratelimit_multi_limit/410_test.go +++ b/svc/api/routes/v2_ratelimit_multi_limit/410_test.go @@ -22,7 +22,6 @@ func TestSoftDeletedNamespace(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Ratelimit: h.Ratelimit, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, Auditlogs: h.Auditlogs, diff --git a/svc/api/routes/v2_ratelimit_multi_limit/BUILD.bazel b/svc/api/routes/v2_ratelimit_multi_limit/BUILD.bazel index 1f3c85f12e..bcecddc8a1 100644 --- a/svc/api/routes/v2_ratelimit_multi_limit/BUILD.bazel +++ b/svc/api/routes/v2_ratelimit_multi_limit/BUILD.bazel @@ -17,8 +17,8 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", + "//pkg/logger", "//pkg/match", - "//pkg/otel/logging", "//pkg/ptr", "//pkg/rbac", "//pkg/uid", diff --git a/svc/api/routes/v2_ratelimit_multi_limit/handler.go b/svc/api/routes/v2_ratelimit_multi_limit/handler.go index 504e84f96b..bd9acc66f0 100644 --- a/svc/api/routes/v2_ratelimit_multi_limit/handler.go +++ b/svc/api/routes/v2_ratelimit_multi_limit/handler.go @@ -19,8 +19,8 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/match" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" @@ -35,7 +35,6 @@ type ( // Handler implements zen.Route interface for the v2 ratelimit multiLimit endpoint type Handler struct { - Logger logging.Logger Keys keys.KeyService DB db.Database ClickHouse clickhouse.Bufferer @@ -116,7 +115,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { overrides, err := db.UnmarshalNullableJSONTo[[]db.FindRatelimitNamespaceLimitOverride](row.Overrides) if err != nil { - h.Logger.Error("failed to unmarshal overrides", "err", err) + logger.Error("failed to unmarshal overrides", "err", err) } for _, override := range overrides { @@ -203,7 +202,7 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { header := s.Request().Header.Get("X-Test-Time") if header != "" { if ts, parseErr := strconv.ParseInt(header, 10, 64); parseErr != nil { - h.Logger.Warn("invalid test time", "header", header) + logger.Warn("invalid test time", "header", header) } else { reqTime = time.UnixMilli(ts) } diff --git a/svc/api/routes/v2_ratelimit_set_override/200_test.go b/svc/api/routes/v2_ratelimit_set_override/200_test.go index cdbce1eda1..a724e534f6 100644 --- a/svc/api/routes/v2_ratelimit_set_override/200_test.go +++ b/svc/api/routes/v2_ratelimit_set_override/200_test.go @@ -32,7 +32,6 @@ func TestSetOverrideSuccessfully(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_set_override/400_test.go b/svc/api/routes/v2_ratelimit_set_override/400_test.go index 1e70dd7d42..ea2e024d21 100644 --- a/svc/api/routes/v2_ratelimit_set_override/400_test.go +++ b/svc/api/routes/v2_ratelimit_set_override/400_test.go @@ -19,7 +19,6 @@ func TestBadRequests(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_set_override/401_test.go b/svc/api/routes/v2_ratelimit_set_override/401_test.go index 27bed01d95..d139b08eed 100644 --- a/svc/api/routes/v2_ratelimit_set_override/401_test.go +++ b/svc/api/routes/v2_ratelimit_set_override/401_test.go @@ -16,7 +16,6 @@ func TestUnauthorizedAccess(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_set_override/403_test.go b/svc/api/routes/v2_ratelimit_set_override/403_test.go index c3e1852a66..d3075902a6 100644 --- a/svc/api/routes/v2_ratelimit_set_override/403_test.go +++ b/svc/api/routes/v2_ratelimit_set_override/403_test.go @@ -33,7 +33,6 @@ func TestWorkspacePermissions(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_set_override/404_test.go b/svc/api/routes/v2_ratelimit_set_override/404_test.go index c15fe9a3bc..0a70ea8c8d 100644 --- a/svc/api/routes/v2_ratelimit_set_override/404_test.go +++ b/svc/api/routes/v2_ratelimit_set_override/404_test.go @@ -17,7 +17,6 @@ func TestNamespaceNotFound(t *testing.T) { route := &handler.Handler{ DB: h.DB, Keys: h.Keys, - Logger: h.Logger, Auditlogs: h.Auditlogs, RatelimitNamespaceCache: h.Caches.RatelimitNamespace, } diff --git a/svc/api/routes/v2_ratelimit_set_override/BUILD.bazel b/svc/api/routes/v2_ratelimit_set_override/BUILD.bazel index 22cf756dc4..b2398b57ff 100644 --- a/svc/api/routes/v2_ratelimit_set_override/BUILD.bazel +++ b/svc/api/routes/v2_ratelimit_set_override/BUILD.bazel @@ -13,7 +13,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/rbac", "//pkg/uid", "//pkg/zen", diff --git a/svc/api/routes/v2_ratelimit_set_override/handler.go b/svc/api/routes/v2_ratelimit_set_override/handler.go index ecd17b0832..af40769c84 100644 --- a/svc/api/routes/v2_ratelimit_set_override/handler.go +++ b/svc/api/routes/v2_ratelimit_set_override/handler.go @@ -14,7 +14,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/pkg/zen" @@ -28,8 +27,6 @@ type ( // Handler implements zen.Route interface for the v2 ratelimit set override endpoint type Handler struct { - // Services as public fields - Logger logging.Logger DB db.Database Keys keys.KeyService Auditlogs auditlogs.AuditLogService diff --git a/svc/api/run.go b/svc/api/run.go index b08d76e8be..d0c75e5415 100644 --- a/svc/api/run.go +++ b/svc/api/run.go @@ -23,8 +23,8 @@ import ( "github.com/unkeyed/unkey/pkg/counter" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/eventstream" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/prometheus" "github.com/unkeyed/unkey/pkg/rbac" "github.com/unkeyed/unkey/pkg/rpc/interceptor" @@ -44,6 +44,24 @@ func Run(ctx context.Context, cfg Config) error { return fmt.Errorf("bad config: %w", err) } + logger.SetSampler(logger.TailSampler{ + SlowThreshold: cfg.LogSlowThreshold, + SampleRate: cfg.LogSampleRate, + }) + logger.AddBaseAttrs(slog.GroupAttrs("instance", + slog.String("id", cfg.InstanceID), + slog.String("platform", cfg.Platform), + slog.String("region", cfg.Region), + slog.String("version", version.Version), + )) + + if cfg.TestMode { + logger.AddBaseAttrs(slog.Bool("testmode", true)) + } + if cfg.TLSConfig != nil { + logger.AddBaseAttrs(slog.Bool("tls_enabled", true)) + } + clk := clock.New() // This is a little ugly, but the best we can do to resolve the circular dependency until we rework the logger. @@ -61,33 +79,7 @@ func Run(ctx context.Context, cfg Config) error { } } - logger := logging.New() - if cfg.InstanceID != "" { - logger = logger.With(slog.String("instanceID", cfg.InstanceID)) - } - - if cfg.Platform != "" { - logger = logger.With(slog.String("platform", cfg.Platform)) - } - - if cfg.Region != "" { - logger = logger.With(slog.String("region", cfg.Region)) - } - - if version.Version != "" { - logger = logger.With(slog.String("version", version.Version)) - } - - if cfg.TestMode { - logger = logger.With("testmode", true) - logger.Warn("TESTMODE IS ENABLED. This is not secure in production!") - } - - if cfg.TLSConfig != nil { - logger.Info("TLS is enabled, server will use HTTPS") - } - - r := runner.New(logger) + r := runner.New() defer r.Recover() r.DeferCtx(shutdownGrafana) @@ -95,7 +87,6 @@ func Run(ctx context.Context, cfg Config) error { db, err := db.New(db.Config{ PrimaryDSN: cfg.DatabasePrimary, ReadOnlyDSN: cfg.DatabaseReadonlyReplica, - Logger: logger, }) if err != nil { return fmt.Errorf("unable to create db: %w", err) @@ -104,9 +95,7 @@ func Run(ctx context.Context, cfg Config) error { r.Defer(db.Close) if cfg.PrometheusPort > 0 { - prom, promErr := prometheus.New(prometheus.Config{ - Logger: logger, - }) + prom, promErr := prometheus.New() if promErr != nil { return fmt.Errorf("unable to start prometheus: %w", promErr) } @@ -129,8 +118,7 @@ func Run(ctx context.Context, cfg Config) error { var ch clickhouse.ClickHouse = clickhouse.NewNoop() if cfg.ClickhouseURL != "" { ch, err = clickhouse.New(clickhouse.Config{ - URL: cfg.ClickhouseURL, - Logger: logger, + URL: cfg.ClickhouseURL, }) if err != nil { return fmt.Errorf("unable to create clickhouse: %w", err) @@ -139,7 +127,6 @@ func Run(ctx context.Context, cfg Config) error { // Caches will be created after invalidation consumer is set up srv, err := zen.New(zen.Config{ - Logger: logger, Flags: &zen.Flags{ TestMode: cfg.TestMode, }, @@ -163,14 +150,12 @@ func Run(ctx context.Context, cfg Config) error { ctr, err := counter.NewRedis(counter.RedisConfig{ RedisURL: cfg.RedisUrl, - Logger: logger, }) if err != nil { return fmt.Errorf("unable to create counter: %w", err) } rlSvc, err := ratelimit.New(ratelimit.Config{ - Logger: logger, Clock: clk, Counter: ctr, }) @@ -182,7 +167,6 @@ func Run(ctx context.Context, cfg Config) error { r.Defer(rlSvc.Close) ulSvc, err := usagelimiter.NewRedisWithCounter(usagelimiter.RedisConfig{ - Logger: logger, DB: db, Counter: ctr, TTL: 60 * time.Second, @@ -195,7 +179,6 @@ func Run(ctx context.Context, cfg Config) error { if len(cfg.VaultMasterKeys) > 0 && cfg.VaultS3 != nil { var vaultStorage storage.Storage vaultStorage, err = storage.NewS3(storage.S3Config{ - Logger: logger, S3URL: cfg.VaultS3.URL, S3Bucket: cfg.VaultS3.Bucket, S3AccessKeyID: cfg.VaultS3.AccessKeyID, @@ -206,7 +189,6 @@ func Run(ctx context.Context, cfg Config) error { } vaultSvc, err = vault.New(vault.Config{ - Logger: logger, Storage: vaultStorage, MasterKeys: cfg.VaultMasterKeys, }) @@ -216,8 +198,7 @@ func Run(ctx context.Context, cfg Config) error { } auditlogSvc, err := auditlogs.New(auditlogs.Config{ - Logger: logger, - DB: db, + DB: db, }) if err != nil { return fmt.Errorf("unable to create auditlogs service: %w", err) @@ -237,7 +218,6 @@ func Run(ctx context.Context, cfg Config) error { Brokers: cfg.KafkaBrokers, Topic: topicName, InstanceID: cfg.InstanceID, - Logger: logger, }) if err != nil { return fmt.Errorf("unable to create cache invalidation topic: %w", err) @@ -248,7 +228,6 @@ func Run(ctx context.Context, cfg Config) error { } caches, err := caches.New(caches.Config{ - Logger: logger, Clock: clk, CacheInvalidationTopic: cacheInvalidationTopic, NodeID: cfg.InstanceID, @@ -258,7 +237,6 @@ func Run(ctx context.Context, cfg Config) error { } keySvc, err := keys.New(keys.Config{ - Logger: logger, DB: db, KeyCache: caches.VerificationKeyByHash, RateLimiter: rlSvc, @@ -280,7 +258,6 @@ func Run(ctx context.Context, cfg Config) error { analyticsConnMgr, err = analytics.NewConnectionManager(analytics.ConnectionManagerConfig{ SettingsCache: caches.ClickhouseSetting, Database: db, - Logger: logger, Clock: clk, BaseURL: cfg.ClickhouseAnalyticsURL, Vault: vaultSvc, @@ -302,7 +279,6 @@ func Run(ctx context.Context, cfg Config) error { logger.Info("CTRL clients initialized", "url", cfg.CtrlURL) routes.Register(srv, &routes.Services{ - Logger: logger, Database: db, ClickHouse: ch, Keys: keySvc, diff --git a/svc/ctrl/api/BUILD.bazel b/svc/ctrl/api/BUILD.bazel index c94e3f2776..3128132d4d 100644 --- a/svc/ctrl/api/BUILD.bazel +++ b/svc/ctrl/api/BUILD.bazel @@ -19,8 +19,8 @@ go_library( "//pkg/clock", "//pkg/db", "//pkg/db/types", + "//pkg/logger", "//pkg/otel", - "//pkg/otel/logging", "//pkg/prometheus", "//pkg/restate/admin", "//pkg/runner", @@ -55,7 +55,7 @@ go_test( "//gen/proto/hydra/v1:hydra", "//pkg/db", "//pkg/dockertest", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/uid", "//svc/ctrl/integration/seed", "@com_connectrpc_connect//:connect", diff --git a/svc/ctrl/api/certificate.go b/svc/ctrl/api/certificate.go index 19b9954b69..fda60bcff8 100644 --- a/svc/ctrl/api/certificate.go +++ b/svc/ctrl/api/certificate.go @@ -7,7 +7,7 @@ import ( "time" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/uid" ) @@ -15,7 +15,6 @@ import ( // This ensures wildcard certificates exist for the default domain // and regional apex domains. type certificateBootstrap struct { - logger logging.Logger database db.Database defaultDomain string regionalDomain string @@ -56,11 +55,11 @@ func (c *certificateBootstrap) bootstrapDomain(ctx context.Context, domain strin // Check if the domain already exists _, err := db.Query.FindCustomDomainByDomain(ctx, c.database.RO(), domain) if err == nil { - c.logger.Info("Domain already exists", "domain", domain) + logger.Info("Domain already exists", "domain", domain) return } if !db.IsNotFound(err) { - c.logger.Error("Failed to check for existing domain", "error", err, "domain", domain) + logger.Error("Failed to check for existing domain", "error", err, "domain", domain) return } @@ -85,7 +84,7 @@ func (c *certificateBootstrap) bootstrapDomain(ctx context.Context, domain strin UpdatedAt: sql.NullInt64{Int64: now, Valid: true}, }) if err != nil { - c.logger.Error("Failed to create domain", "error", err, "domain", domain) + logger.Error("Failed to create domain", "error", err, "domain", domain) return } @@ -102,9 +101,9 @@ func (c *certificateBootstrap) bootstrapDomain(ctx context.Context, domain strin ExpiresAt: 0, // Will be set when certificate is issued }) if err != nil { - c.logger.Error("Failed to create ACME challenge for domain", "error", err, "domain", domain) + logger.Error("Failed to create ACME challenge for domain", "error", err, "domain", domain) return } - c.logger.Info("Bootstrapped domain for certificate issuance", "domain", domain) + logger.Info("Bootstrapped domain for certificate issuance", "domain", domain) } diff --git a/svc/ctrl/api/github_webhook.go b/svc/ctrl/api/github_webhook.go index c15089e796..3aaeab73df 100644 --- a/svc/ctrl/api/github_webhook.go +++ b/svc/ctrl/api/github_webhook.go @@ -13,7 +13,7 @@ import ( hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" dbtype "github.com/unkeyed/unkey/pkg/db/types" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/uid" githubclient "github.com/unkeyed/unkey/svc/ctrl/worker/github" ) @@ -25,7 +25,6 @@ const maxWebhookBodySize = 2 * 1024 * 1024 // 2 MB // the configured secret before processing any events. type GitHubWebhook struct { db db.Database - logger logging.Logger restate *restateingress.Client webhookSecret string } @@ -34,14 +33,14 @@ type GitHubWebhook struct { // handlers. Currently supports push events for triggering deployments. // Unknown event types are acknowledged with 200 OK but not processed. func (s *GitHubWebhook) ServeHTTP(w http.ResponseWriter, r *http.Request) { - s.logger.Info("GitHub webhook request received", + logger.Info("GitHub webhook request received", "method", r.Method, "path", r.URL.Path, "remote_addr", r.RemoteAddr, ) if r.Method != http.MethodPost { - s.logger.Warn("GitHub webhook rejected: method not allowed", "method", r.Method) + logger.Warn("GitHub webhook rejected: method not allowed", "method", r.Method) http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } @@ -54,7 +53,7 @@ func (s *GitHubWebhook) ServeHTTP(w http.ResponseWriter, r *http.Request) { signature := r.Header.Get("X-Hub-Signature-256") if signature == "" { - s.logger.Warn("GitHub webhook rejected: missing signature header") + logger.Warn("GitHub webhook rejected: missing signature header") http.Error(w, "missing X-Hub-Signature-256 header", http.StatusUnauthorized) return } @@ -62,27 +61,27 @@ func (s *GitHubWebhook) ServeHTTP(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxWebhookBodySize)) if err != nil { - s.logger.Warn("GitHub webhook rejected: failed to read body", "error", err) + logger.Warn("GitHub webhook rejected: failed to read body", "error", err) http.Error(w, "failed to read body", http.StatusBadRequest) return } if !githubclient.VerifyWebhookSignature(body, signature, s.webhookSecret) { - s.logger.Warn("GitHub webhook rejected: invalid signature") + logger.Warn("GitHub webhook rejected: invalid signature") http.Error(w, "invalid signature", http.StatusUnauthorized) return } - s.logger.Info("GitHub webhook signature verified", "event", event) + logger.Info("GitHub webhook signature verified", "event", event) switch event { case "push": s.handlePush(r.Context(), w, body) case "installation": - s.logger.Info("Installation event received") + logger.Info("Installation event received") w.WriteHeader(http.StatusOK) default: - s.logger.Info("Unhandled event type", "event", event) + logger.Info("Unhandled event type", "event", event) w.WriteHeader(http.StatusOK) } @@ -94,14 +93,14 @@ func (s *GitHubWebhook) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (s *GitHubWebhook) handlePush(ctx context.Context, w http.ResponseWriter, body []byte) { var payload pushPayload if err := json.Unmarshal(body, &payload); err != nil { - s.logger.Error("failed to parse push payload", "error", err) + logger.Error("failed to parse push payload", "error", err) http.Error(w, "failed to parse push payload", http.StatusBadRequest) return } branch := extractBranchFromRef(payload.Ref) if branch == "" { - s.logger.Info("Ignoring non-branch push", "ref", payload.Ref) + logger.Info("Ignoring non-branch push", "ref", payload.Ref) w.WriteHeader(http.StatusOK) return } @@ -112,11 +111,11 @@ func (s *GitHubWebhook) handlePush(ctx context.Context, w http.ResponseWriter, b }) if err != nil { if db.IsNotFound(err) { - s.logger.Info("No repo connection found for repository", "repository", payload.Repository.FullName) + logger.Info("No repo connection found for repository", "repository", payload.Repository.FullName) w.WriteHeader(http.StatusOK) return } - s.logger.Error("failed to find repo connection", "error", err, "repository", payload.Repository.FullName) + logger.Error("failed to find repo connection", "error", err, "repository", payload.Repository.FullName) http.Error(w, "failed to find repo connection", http.StatusInternalServerError) return } @@ -124,11 +123,11 @@ func (s *GitHubWebhook) handlePush(ctx context.Context, w http.ResponseWriter, b project, err := db.Query.FindProjectById(ctx, s.db.RO(), repoConnection.ProjectID) if err != nil { if db.IsNotFound(err) { - s.logger.Info("No project found for repo connection", "projectId", repoConnection.ProjectID) + logger.Info("No project found for repo connection", "projectId", repoConnection.ProjectID) w.WriteHeader(http.StatusOK) return } - s.logger.Error("failed to find project", "error", err, "projectId", repoConnection.ProjectID) + logger.Error("failed to find project", "error", err, "projectId", repoConnection.ProjectID) http.Error(w, "failed to find project", http.StatusInternalServerError) return } @@ -150,7 +149,7 @@ func (s *GitHubWebhook) handlePush(ctx context.Context, w http.ResponseWriter, b Slug: envSlug, }) if err != nil { - s.logger.Error("failed to find environment", "error", err, "projectId", project.ID, "envSlug", envSlug) + logger.Error("failed to find environment", "error", err, "projectId", project.ID, "envSlug", envSlug) http.Error(w, "failed to find environment", http.StatusInternalServerError) return } @@ -183,12 +182,12 @@ func (s *GitHubWebhook) handlePush(ctx context.Context, w http.ResponseWriter, b MemoryMib: 256, }) if err != nil { - s.logger.Error("failed to insert deployment", "error", err) + logger.Error("failed to insert deployment", "error", err) http.Error(w, "failed to create deployment", http.StatusInternalServerError) return } - s.logger.Info("Created deployment record", + logger.Info("Created deployment record", "deployment_id", deploymentID, "project_id", project.ID, "repository", payload.Repository.FullName, @@ -212,12 +211,12 @@ func (s *GitHubWebhook) handlePush(ctx context.Context, w http.ResponseWriter, b }, }) if err != nil { - s.logger.Error("failed to start deployment workflow", "error", err) + logger.Error("failed to start deployment workflow", "error", err) http.Error(w, "failed to start workflow", http.StatusInternalServerError) return } - s.logger.Info("Deployment workflow started", + logger.Info("Deployment workflow started", "invocation_id", invocation.Id, "deployment_id", deploymentID, "project_id", project.ID, diff --git a/svc/ctrl/api/harness_test.go b/svc/ctrl/api/harness_test.go index f381643b3f..93b2af1376 100644 --- a/svc/ctrl/api/harness_test.go +++ b/svc/ctrl/api/harness_test.go @@ -19,7 +19,7 @@ import ( "github.com/stretchr/testify/require" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/dockertest" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/svc/ctrl/integration/seed" "golang.org/x/net/http2" @@ -47,7 +47,7 @@ func newWebhookHarness(t *testing.T, cfg webhookHarnessConfig) *webhookHarness { restateCfg := dockertest.Restate(t) - restateSrv := restateServer.NewRestate().WithLogger(logging.Handler(), false) + restateSrv := restateServer.NewRestate().WithLogger(logger.GetHandler(), false) for _, service := range cfg.Services { restateSrv.Bind(service) } @@ -74,7 +74,6 @@ func newWebhookHarness(t *testing.T, cfg webhookHarnessConfig) *webhookHarness { mysqlCfg := dockertest.MySQL(t) database, err := db.New(db.Config{ - Logger: logging.NewNoop(), PrimaryDSN: mysqlCfg.DSN, ReadOnlyDSN: "", }) diff --git a/svc/ctrl/api/run.go b/svc/ctrl/api/run.go index 8cfd5e5333..ccb89aa407 100644 --- a/svc/ctrl/api/run.go +++ b/svc/ctrl/api/run.go @@ -15,8 +15,8 @@ import ( "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/prometheus" restateadmin "github.com/unkeyed/unkey/pkg/restate/admin" "github.com/unkeyed/unkey/pkg/runner" @@ -68,22 +68,18 @@ func Run(ctx context.Context, cfg Config) error { } } - logger := logging.New() - if cfg.InstanceID != "" { - logger = logger.With(slog.String("instanceID", cfg.InstanceID)) - } - if cfg.Region != "" { - logger = logger.With(slog.String("region", cfg.Region)) - } - if pkgversion.Version != "" { - logger = logger.With(slog.String("version", pkgversion.Version)) - } + // Add base attributes to global logger + logger.AddBaseAttrs(slog.GroupAttrs("instance", + slog.String("id", cfg.InstanceID), + slog.String("region", cfg.Region), + slog.String("version", pkgversion.Version), + )) if cfg.TLSConfig != nil { logger.Info("TLS is enabled, server will use HTTPS") } - r := runner.New(logger) + r := runner.New() defer r.Recover() r.DeferCtx(shutdownGrafana) @@ -92,7 +88,6 @@ func Run(ctx context.Context, cfg Config) error { database, err := db.New(db.Config{ PrimaryDSN: cfg.DatabasePrimary, ReadOnlyDSN: "", - Logger: logger, }) if err != nil { return fmt.Errorf("unable to create db: %w", err) @@ -115,7 +110,6 @@ func Run(ctx context.Context, cfg Config) error { c := cluster.New(cluster.Config{ Database: database, - Logger: logger, Bearer: cfg.AuthToken, }) @@ -125,7 +119,6 @@ func Run(ctx context.Context, cfg Config) error { Fresh: 5 * time.Minute, Stale: 10 * time.Minute, MaxSize: 10000, - Logger: logger, Resource: "domains", Clock: clk, }) @@ -137,7 +130,6 @@ func Run(ctx context.Context, cfg Config) error { Fresh: 10 * time.Second, Stale: 30 * time.Second, MaxSize: 1000, - Logger: logger, Resource: "acme_challenges", Clock: clk, }) @@ -154,14 +146,12 @@ func Run(ctx context.Context, cfg Config) error { mux.Handle(ctrlv1connect.NewDeploymentServiceHandler(deployment.New(deployment.Config{ Database: database, Restate: restateClient, - Logger: logger, AvailableRegions: cfg.AvailableRegions, }))) - mux.Handle(ctrlv1connect.NewOpenApiServiceHandler(openapi.New(database, logger))) + mux.Handle(ctrlv1connect.NewOpenApiServiceHandler(openapi.New(database))) mux.Handle(ctrlv1connect.NewAcmeServiceHandler(acme.New(acme.Config{ DB: database, - Logger: logger, DomainCache: domainCache, ChallengeCache: challengeCache, }))) @@ -170,14 +160,12 @@ func Run(ctx context.Context, cfg Config) error { Database: database, Restate: restateClient, RestateAdmin: restateAdminClient, - Logger: logger, CnameDomain: cfg.CnameDomain, }))) if cfg.GitHubWebhookSecret != "" { mux.Handle("POST /webhooks/github", &GitHubWebhook{ db: database, - logger: logger, restate: restateClient, webhookSecret: cfg.GitHubWebhookSecret, }) @@ -240,7 +228,6 @@ func Run(ctx context.Context, cfg Config) error { // Bootstrap certificates (wildcard domain records) if cfg.DefaultDomain != "" { certBootstrap := &certificateBootstrap{ - logger: logger, database: database, defaultDomain: cfg.DefaultDomain, regionalDomain: cfg.RegionalDomain, @@ -253,9 +240,7 @@ func Run(ctx context.Context, cfg Config) error { } if cfg.PrometheusPort > 0 { - prom, promErr := prometheus.New(prometheus.Config{ - Logger: logger, - }) + prom, promErr := prometheus.New() if promErr != nil { return fmt.Errorf("failed to create prometheus server: %w", promErr) } diff --git a/svc/ctrl/integration/BUILD.bazel b/svc/ctrl/integration/BUILD.bazel index ec2fcdaa3f..2777a3d540 100644 --- a/svc/ctrl/integration/BUILD.bazel +++ b/svc/ctrl/integration/BUILD.bazel @@ -8,7 +8,6 @@ go_library( deps = [ "//pkg/db", "//pkg/dockertest", - "//pkg/otel/logging", "//pkg/uid", "//svc/ctrl/integration/seed", "@com_github_stretchr_testify//require", diff --git a/svc/ctrl/integration/harness.go b/svc/ctrl/integration/harness.go index 6944c28473..be6b3f358c 100644 --- a/svc/ctrl/integration/harness.go +++ b/svc/ctrl/integration/harness.go @@ -9,7 +9,6 @@ import ( "github.com/stretchr/testify/require" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/dockertest" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/svc/ctrl/integration/seed" ) @@ -34,7 +33,6 @@ func New(t *testing.T) *Harness { mysqlHostDSN := mysqlCfg.DSN database, err := db.New(db.Config{ - Logger: logging.NewNoop(), PrimaryDSN: mysqlHostDSN, ReadOnlyDSN: "", }) diff --git a/svc/ctrl/integration/harness/BUILD.bazel b/svc/ctrl/integration/harness/BUILD.bazel index 57e37a7713..05f4fed231 100644 --- a/svc/ctrl/integration/harness/BUILD.bazel +++ b/svc/ctrl/integration/harness/BUILD.bazel @@ -12,7 +12,6 @@ go_library( "//pkg/db", "//pkg/dockertest", "//pkg/healthcheck", - "//pkg/otel/logging", "//pkg/restate/admin", "//svc/ctrl/integration/seed", "//svc/ctrl/worker/clickhouseuser", diff --git a/svc/ctrl/integration/harness/harness.go b/svc/ctrl/integration/harness/harness.go index 09fe4b940f..4f656c79ad 100644 --- a/svc/ctrl/integration/harness/harness.go +++ b/svc/ctrl/integration/harness/harness.go @@ -24,7 +24,6 @@ import ( "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/dockertest" "github.com/unkeyed/unkey/pkg/healthcheck" - "github.com/unkeyed/unkey/pkg/otel/logging" restateadmin "github.com/unkeyed/unkey/pkg/restate/admin" "github.com/unkeyed/unkey/svc/ctrl/integration/seed" "github.com/unkeyed/unkey/svc/ctrl/worker/clickhouseuser" @@ -126,7 +125,6 @@ func New(t *testing.T) *Harness { // Connect to MySQL database, err := db.New(db.Config{ - Logger: logging.NewNoop(), PrimaryDSN: mysqlCfg.DSN, ReadOnlyDSN: "", }) @@ -136,8 +134,7 @@ func New(t *testing.T) *Harness { // Connect to ClickHouse chDSN := chCfg.DSN chClient, err := clickhouse.New(clickhouse.Config{ - URL: chDSN, - Logger: logging.NewNoop(), + URL: chDSN, }) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, chClient.Close()) }) @@ -156,7 +153,6 @@ func New(t *testing.T) *Harness { quotaCheckSvc, err := quotacheck.New(quotacheck.Config{ DB: database, Clickhouse: chClient, - Logger: logging.NewNoop(), Heartbeat: healthcheck.NewNoop(), SlackWebhookURL: "", }) @@ -166,12 +162,11 @@ func New(t *testing.T) *Harness { DB: database, Vault: testVault.Client, Clickhouse: chClient, - Logger: logging.NewNoop(), }) // Set up Restate server with all services // Use the proto-generated wrappers (same as run.go) to get correct service names - restateSrv := restateServer.NewRestate().WithLogger(logging.Handler(), false) + restateSrv := restateServer.NewRestate() restateSrv.Bind(hydrav1.NewQuotaCheckServiceServer(quotaCheckSvc)) restateSrv.Bind(hydrav1.NewClickhouseUserServiceServer(clickhouseUserSvc)) diff --git a/svc/ctrl/integration/sync_test.go b/svc/ctrl/integration/sync_test.go index e12a7feaca..09ae59862f 100644 --- a/svc/ctrl/integration/sync_test.go +++ b/svc/ctrl/integration/sync_test.go @@ -41,7 +41,6 @@ import ( "github.com/stretchr/testify/require" ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/svc/ctrl/services/cluster" ) @@ -84,7 +83,6 @@ func (m *mockStream) ResponseTrailer() http.Header { func newService(t *testing.T, database db.Database) *cluster.Service { return cluster.New(cluster.Config{ Database: database, - Logger: logging.NewNoop(), Bearer: "test-bearer", }) } diff --git a/svc/ctrl/pkg/s3/BUILD.bazel b/svc/ctrl/pkg/s3/BUILD.bazel deleted file mode 100644 index 63940e168e..0000000000 --- a/svc/ctrl/pkg/s3/BUILD.bazel +++ /dev/null @@ -1,40 +0,0 @@ -load("@rules_go//go:def.bzl", "go_library") - -go_library( - name = "storage", - srcs = [ - "doc.go", - "s3.go", - ], - importpath = "github.com/unkeyed/unkey/svc/ctrl/services/build/storage", - visibility = ["//visibility:public"], - deps = [ - "//pkg/fault", - "//pkg/otel/logging", - "@com_github_aws_aws_sdk_go_v2//aws", - "@com_github_aws_aws_sdk_go_v2//aws/signer/v4:signer", - "@com_github_aws_aws_sdk_go_v2_config//:config", - "@com_github_aws_aws_sdk_go_v2_credentials//:credentials", - "@com_github_aws_aws_sdk_go_v2_service_s3//:s3", - ], -) - -go_library( - name = "s3", - srcs = [ - "doc.go", - "interface.go", - "s3.go", - ], - importpath = "github.com/unkeyed/unkey/svc/ctrl/pkg/s3", - visibility = ["//visibility:public"], - deps = [ - "//pkg/fault", - "//pkg/otel/logging", - "@com_github_aws_aws_sdk_go_v2//aws", - "@com_github_aws_aws_sdk_go_v2//aws/signer/v4:signer", - "@com_github_aws_aws_sdk_go_v2_config//:config", - "@com_github_aws_aws_sdk_go_v2_credentials//:credentials", - "@com_github_aws_aws_sdk_go_v2_service_s3//:s3", - ], -) diff --git a/svc/ctrl/pkg/s3/doc.go b/svc/ctrl/pkg/s3/doc.go deleted file mode 100644 index 2470435877..0000000000 --- a/svc/ctrl/pkg/s3/doc.go +++ /dev/null @@ -1,33 +0,0 @@ -// Package s3 provides pre-signed URL generation for S3-compatible object storage. -// -// The package supports separate internal and external S3 endpoints, which is -// necessary when the service runs inside a Docker network but clients access -// storage from outside. For example, the service may communicate with MinIO at -// http://minio:9000 internally, while clients need URLs pointing to -// http://localhost:9000. -// -// # Key Types -// -// [S3] is the main client that implements the [Storage] interface. Create one -// with [NewS3] using [S3Config] for configuration. -// -// # Usage -// -// s3Client, err := s3.NewS3(s3.S3Config{ -// Logger: logger, -// S3URL: "http://minio:9000", -// S3PresignURL: "http://localhost:9000", -// S3Bucket: "artifacts", -// S3AccessKeyID: "access-key", -// S3AccessKeySecret: "secret-key", -// }) -// if err != nil { -// // Handle error - bucket creation or AWS config failed -// } -// -// // Generate a URL for clients to upload an artifact -// uploadURL, err := s3Client.GenerateUploadURL(ctx, "builds/123/artifact.tar.gz", time.Hour) -// -// // Generate a URL for clients to download an artifact -// downloadURL, err := s3Client.GenerateDownloadURL(ctx, "builds/123/artifact.tar.gz", time.Hour) -package s3 diff --git a/svc/ctrl/pkg/s3/interface.go b/svc/ctrl/pkg/s3/interface.go deleted file mode 100644 index 078cd0a3bf..0000000000 --- a/svc/ctrl/pkg/s3/interface.go +++ /dev/null @@ -1,20 +0,0 @@ -package s3 - -import ( - "context" - "time" -) - -// Storage defines the interface for generating pre-signed URLs for object storage. -// Implementations must be safe for concurrent use. -type Storage interface { - // GenerateDownloadURL returns a pre-signed URL that allows downloading the - // object at key. The URL expires after expiresIn. - GenerateDownloadURL(ctx context.Context, key string, expiresIn time.Duration) (string, error) - - // GenerateUploadURL returns a pre-signed URL that allows uploading an object - // to key using HTTP PUT. The URL expires after expiresIn. - GenerateUploadURL(ctx context.Context, key string, expiresIn time.Duration) (string, error) -} - -var _ Storage = (*S3)(nil) diff --git a/svc/ctrl/pkg/s3/s3.go b/svc/ctrl/pkg/s3/s3.go deleted file mode 100644 index 6b749b1565..0000000000 --- a/svc/ctrl/pkg/s3/s3.go +++ /dev/null @@ -1,184 +0,0 @@ -package s3 - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - awsConfig "github.com/aws/aws-sdk-go-v2/config" - "github.com/aws/aws-sdk-go-v2/credentials" - awsS3 "github.com/aws/aws-sdk-go-v2/service/s3" - "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" -) - -// S3 generates pre-signed URLs for S3-compatible object storage. It implements -// the [Storage] interface and is safe for concurrent use. -type S3 struct { - presigner *awsS3.PresignClient - config S3Config - logger logging.Logger -} - -// S3Config holds configuration for connecting to an S3-compatible storage backend. -type S3Config struct { - // S3URL is the endpoint URL used for S3 operations like bucket creation. - // This should be the internal network address when running in Docker. - S3URL string - - // S3PresignURL is the endpoint URL embedded in pre-signed URLs. Clients use - // this URL to access objects, so it must be reachable from outside the - // Docker network. Defaults to S3URL if empty. - S3PresignURL string - - // S3Bucket is the name of the bucket to use. The bucket is created - // automatically by [NewS3] if it does not exist. - S3Bucket string - - // S3AccessKeyID is the access key for S3 authentication. - S3AccessKeyID string - - // S3AccessKeySecret is the secret key for S3 authentication. - S3AccessKeySecret string - - // Logger is used for logging storage operations. - Logger logging.Logger -} - -// NewS3 creates an S3 client configured for pre-signed URL generation. It -// creates the configured bucket if it does not already exist, ignoring the -// "BucketAlreadyOwnedByYou" error. -// -// Returns an error if the AWS configuration cannot be loaded or if bucket -// creation fails for reasons other than the bucket already existing. -func NewS3(config S3Config) (*S3, error) { - logger := config.Logger.With("service", "storage") - - // Internal client config (for actual operations within Docker network) - // This client is used for all actual S3 operations like CreateBucket, PutObject, GetObject - //nolint: staticcheck - internalResolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...any) (aws.Endpoint, error) { - return aws.Endpoint{ - URL: config.S3URL, - HostnameImmutable: true, - }, nil - }) - - internalCfg, err := awsConfig.LoadDefaultConfig(context.Background(), - //nolint: staticcheck - awsConfig.WithEndpointResolverWithOptions(internalResolver), - awsConfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider( - config.S3AccessKeyID, - config.S3AccessKeySecret, - "", - )), - awsConfig.WithRegion("auto"), - ) - if err != nil { - return nil, fault.Wrap(err, fault.Internal("failed to load aws config")) - } - - // Create bucket using internal client - internalClient := awsS3.NewFromConfig(internalCfg) - logger.Info("creating bucket if necessary") - _, err = internalClient.CreateBucket(context.Background(), &awsS3.CreateBucketInput{ - Bucket: aws.String(config.S3Bucket), - }) - if err != nil && !strings.Contains(err.Error(), "BucketAlreadyOwnedByYou") { - return nil, fmt.Errorf("failed to create bucket: %w", err) - } - - // The reason for this check is when testing locally with docker CLI cannot access the internal S3 URL of minio without altering the /etc/host. - // Thats why we conditionally check it and allow consumers of this package to decide, - // but regardless of access URL we need to use internal S3 URL for bucket creation. - presignURL := config.S3PresignURL - if presignURL == "" { - presignURL = config.S3URL // Default to internal - } - - logger.Info("s3 storage initialized", "presign_url", presignURL) - - // Create presigner with the appropriate URL - //nolint: staticcheck - presignResolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...any) (aws.Endpoint, error) { - return aws.Endpoint{ - URL: presignURL, - HostnameImmutable: true, - }, nil - }) - - presignCfg, err := awsConfig.LoadDefaultConfig(context.Background(), - //nolint: staticcheck - awsConfig.WithEndpointResolverWithOptions(presignResolver), - awsConfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider( - config.S3AccessKeyID, - config.S3AccessKeySecret, - "", - )), - awsConfig.WithRegion("auto"), - ) - if err != nil { - return nil, fault.Wrap(err, fault.Internal("failed to load presign config")) - } - - presignClient := awsS3.NewFromConfig(presignCfg) - presigner := awsS3.NewPresignClient(presignClient) - - return &S3{ - presigner: presigner, - config: config, - logger: logger, - }, nil -} - -// GenerateDownloadURL returns a pre-signed URL for downloading the object at -// key. The URL is valid for expiresIn duration and uses the S3PresignURL -// endpoint configured in [S3Config]. -func (s *S3) GenerateDownloadURL(ctx context.Context, key string, expiresIn time.Duration) (string, error) { - return s.presign(ctx, key, expiresIn, "GET") -} - -// GenerateUploadURL returns a pre-signed URL for uploading an object to key -// using HTTP PUT. The URL is valid for expiresIn duration and uses the -// S3PresignURL endpoint configured in [S3Config]. -func (s *S3) GenerateUploadURL(ctx context.Context, key string, expiresIn time.Duration) (string, error) { - return s.presign(ctx, key, expiresIn, "PUT") -} - -func (s *S3) presign(ctx context.Context, key string, expiresIn time.Duration, method string) (string, error) { - logger := s.logger.With("method", method, "key", key, "expires_in", expiresIn.String()) - logger.Debug("presigning URL") - - opts := func(o *awsS3.PresignOptions) { - o.Expires = expiresIn - } - - var req *v4.PresignedHTTPRequest - var err error - - switch method { - case "PUT": - req, err = s.presigner.PresignPutObject(ctx, &awsS3.PutObjectInput{ - Bucket: aws.String(s.config.S3Bucket), - Key: aws.String(key), - }, opts) - case "GET": - req, err = s.presigner.PresignGetObject(ctx, &awsS3.GetObjectInput{ - Bucket: aws.String(s.config.S3Bucket), - Key: aws.String(key), - }, opts) - default: - logger.Error("unsupported HTTP method", "error", fmt.Sprintf("method %s is not supported", method)) - return "", fmt.Errorf("unsupported method: %s", method) - } - - if err != nil { - logger.Error("failed to presign URL", "error", err) - return "", fmt.Errorf("failed to presign %s: %w", method, err) - } - - return req.URL, nil -} diff --git a/svc/ctrl/services/acme/BUILD.bazel b/svc/ctrl/services/acme/BUILD.bazel index 3d474bb445..e503d52eb9 100644 --- a/svc/ctrl/services/acme/BUILD.bazel +++ b/svc/ctrl/services/acme/BUILD.bazel @@ -20,7 +20,7 @@ go_library( "//internal/services/caches", "//pkg/cache", "//pkg/db", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/uid", "@com_connectrpc_connect//:connect", "@com_github_go_acme_lego_v4//acme", diff --git a/svc/ctrl/services/acme/doc.go b/svc/ctrl/services/acme/doc.go index f548f8c7cb..aa50eb042f 100644 --- a/svc/ctrl/services/acme/doc.go +++ b/svc/ctrl/services/acme/doc.go @@ -28,7 +28,6 @@ // // svc := acme.New(acme.Config{ // DB: database, -// Logger: logger, // DomainCache: caches.Domains, // ChallengeCache: caches.Challenges, // }) diff --git a/svc/ctrl/services/acme/providers/BUILD.bazel b/svc/ctrl/services/acme/providers/BUILD.bazel index 8ce5600f5f..cbccb45256 100644 --- a/svc/ctrl/services/acme/providers/BUILD.bazel +++ b/svc/ctrl/services/acme/providers/BUILD.bazel @@ -14,7 +14,7 @@ go_library( "//pkg/assert", "//pkg/cache", "//pkg/db", - "//pkg/otel/logging", + "//pkg/logger", "@com_github_go_acme_lego_v4//challenge", "@com_github_go_acme_lego_v4//providers/dns/route53", ], diff --git a/svc/ctrl/services/acme/providers/http_provider.go b/svc/ctrl/services/acme/providers/http_provider.go index 1e31c21a24..152a155b7a 100644 --- a/svc/ctrl/services/acme/providers/http_provider.go +++ b/svc/ctrl/services/acme/providers/http_provider.go @@ -6,7 +6,7 @@ import ( "github.com/go-acme/lego/v4/challenge" "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) var _ challenge.Provider = (*HTTPProvider)(nil) @@ -15,22 +15,21 @@ var _ challenge.ProviderTimeout = (*HTTPProvider)(nil) // httpDNS implements the DNSProvider interface for HTTP-01 challenges. // It stores challenges in the database where the gateway can retrieve them. type httpDNS struct { - db db.Database - logger logging.Logger + db db.Database } // Present stores the challenge token in the database for the gateway to serve. // The gateway will intercept requests to /.well-known/acme-challenge/{token} // and respond with the keyAuth value. func (h *httpDNS) Present(domain, token, keyAuth string) error { - h.logger.Info("presenting http-01 challenge", "domain", domain) + logger.Info("presenting http-01 challenge", "domain", domain) // The actual DB update is handled by the generic Provider wrapper return nil } // CleanUp is a no-op for HTTP-01 - the token remains in DB until overwritten func (h *httpDNS) CleanUp(domain, token, keyAuth string) error { - h.logger.Info("cleaning up http-01 challenge", "domain", domain) + logger.Info("cleaning up http-01 challenge", "domain", domain) return nil } @@ -46,18 +45,15 @@ type HTTPProvider = Provider type HTTPConfig struct { DB db.Database - Logger logging.Logger DomainCache cache.Cache[string, db.CustomDomain] } // NewHTTPProvider creates a new HTTP-01 challenge provider. func NewHTTPProvider(cfg HTTPConfig) (*HTTPProvider, error) { return NewProvider(ProviderConfig{ - DB: cfg.DB, - Logger: cfg.Logger, + DB: cfg.DB, DNS: &httpDNS{ - db: cfg.DB, - logger: cfg.Logger, + db: cfg.DB, }, DomainCache: cfg.DomainCache, }) diff --git a/svc/ctrl/services/acme/providers/provider.go b/svc/ctrl/services/acme/providers/provider.go index df306e2aaf..1fe4f75174 100644 --- a/svc/ctrl/services/acme/providers/provider.go +++ b/svc/ctrl/services/acme/providers/provider.go @@ -12,7 +12,7 @@ import ( "github.com/unkeyed/unkey/pkg/assert" "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) // ErrDomainNotFound is returned when a domain is not found in the database. @@ -32,15 +32,13 @@ type DNSProvider interface { // Provider wraps a DNS provider with database tracking and caching. // It implements the lego challenge.Provider interface. type Provider struct { - db db.Database - logger logging.Logger - dns DNSProvider - cache cache.Cache[string, db.CustomDomain] + db db.Database + dns DNSProvider + cache cache.Cache[string, db.CustomDomain] } type ProviderConfig struct { DB db.Database - Logger logging.Logger DNS DNSProvider DomainCache cache.Cache[string, db.CustomDomain] } @@ -49,7 +47,6 @@ type ProviderConfig struct { func NewProvider(cfg ProviderConfig) (*Provider, error) { err := assert.All( assert.NotNilAndNotZero(cfg.DB, "db is required"), - assert.NotNilAndNotZero(cfg.Logger, "logger is required"), assert.NotNilAndNotZero(cfg.DNS, "dns provider is required"), assert.NotNilAndNotZero(cfg.DomainCache, "domain cache is required"), ) @@ -58,10 +55,9 @@ func NewProvider(cfg ProviderConfig) (*Provider, error) { } return &Provider{ - db: cfg.DB, - logger: cfg.Logger, - dns: cfg.DNS, - cache: cfg.DomainCache, + db: cfg.DB, + dns: cfg.DNS, + cache: cfg.DomainCache, }, nil } @@ -101,7 +97,7 @@ func (p *Provider) Present(domain, token, keyAuth string) error { return fmt.Errorf("failed to find domain %s: %w", domain, err) } - p.logger.Info("presenting dns challenge", "domain", domain, "matched", dom.Domain) + logger.Info("presenting dns challenge", "domain", domain, "matched", dom.Domain) err = p.dns.Present(domain, token, keyAuth) if err != nil { @@ -119,17 +115,17 @@ func (p *Provider) Present(domain, token, keyAuth string) error { return fmt.Errorf("failed to store challenge for domain %s: %w", domain, err) } - p.logger.Info("dns challenge presented successfully", "domain", domain) + logger.Info("dns challenge presented successfully", "domain", domain) return nil } // CleanUp removes the DNS TXT record. func (p *Provider) CleanUp(domain, token, keyAuth string) error { - p.logger.Info("cleaning up dns challenge", "domain", domain) + logger.Info("cleaning up dns challenge", "domain", domain) err := p.dns.CleanUp(domain, token, keyAuth) if err != nil { - p.logger.Warn("failed to clean up dns challenge record", "error", err, "domain", domain) + logger.Warn("failed to clean up dns challenge record", "error", err, "domain", domain) } return nil diff --git a/svc/ctrl/services/acme/providers/route53_provider.go b/svc/ctrl/services/acme/providers/route53_provider.go index 30326d3b13..c318b4d73e 100644 --- a/svc/ctrl/services/acme/providers/route53_provider.go +++ b/svc/ctrl/services/acme/providers/route53_provider.go @@ -7,12 +7,11 @@ import ( "github.com/go-acme/lego/v4/providers/dns/route53" "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) type Route53Config struct { DB db.Database - Logger logging.Logger AccessKeyID string SecretAccessKey string Region string @@ -44,7 +43,7 @@ func NewRoute53Provider(cfg Route53Config) (*Provider, error) { config.HostedZoneID = cfg.HostedZoneID } - cfg.Logger.Info("Route53 provider configured", + logger.Info("Route53 provider configured", "region", cfg.Region, "hosted_zone_id", cfg.HostedZoneID, ) @@ -56,7 +55,6 @@ func NewRoute53Provider(cfg Route53Config) (*Provider, error) { return NewProvider(ProviderConfig{ DB: cfg.DB, - Logger: cfg.Logger, DNS: dns, DomainCache: cfg.DomainCache, }) diff --git a/svc/ctrl/services/acme/service.go b/svc/ctrl/services/acme/service.go index da9ccaeacb..a1c0529538 100644 --- a/svc/ctrl/services/acme/service.go +++ b/svc/ctrl/services/acme/service.go @@ -4,20 +4,17 @@ import ( "github.com/unkeyed/unkey/gen/proto/ctrl/v1/ctrlv1connect" "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) type Service struct { ctrlv1connect.UnimplementedAcmeServiceHandler db db.Database - logger logging.Logger domainCache cache.Cache[string, db.CustomDomain] challengeCache cache.Cache[string, db.AcmeChallenge] } type Config struct { DB db.Database - Logger logging.Logger DomainCache cache.Cache[string, db.CustomDomain] ChallengeCache cache.Cache[string, db.AcmeChallenge] } @@ -26,7 +23,6 @@ func New(cfg Config) *Service { return &Service{ UnimplementedAcmeServiceHandler: ctrlv1connect.UnimplementedAcmeServiceHandler{}, db: cfg.DB, - logger: cfg.Logger, domainCache: cfg.DomainCache, challengeCache: cfg.ChallengeCache, } diff --git a/svc/ctrl/services/acme/user.go b/svc/ctrl/services/acme/user.go index 94e736c01e..01c2417021 100644 --- a/svc/ctrl/services/acme/user.go +++ b/svc/ctrl/services/acme/user.go @@ -16,7 +16,7 @@ import ( vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" "github.com/unkeyed/unkey/gen/proto/vault/v1/vaultv1connect" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/uid" ) @@ -41,7 +41,6 @@ func (u *AcmeUser) GetPrivateKey() crypto.PrivateKey { type UserConfig struct { DB db.Database - Logger logging.Logger Vault vaultv1connect.VaultServiceClient WorkspaceID string EmailDomain string // Domain for ACME registration emails (e.g., "unkey.com") @@ -92,7 +91,7 @@ func GetOrCreateUser(ctx context.Context, cfg UserConfig) (*lego.Client, error) // If user exists but doesn't have a registration URI, complete the registration if !foundUser.RegistrationUri.Valid || foundUser.RegistrationUri.String == "" { - cfg.Logger.Info("acme user missing registration, completing registration", + logger.Info("acme user missing registration, completing registration", "workspace_id", cfg.WorkspaceID, ) @@ -107,7 +106,7 @@ func GetOrCreateUser(ctx context.Context, cfg UserConfig) (*lego.Client, error) ID: foundUser.ID, RegistrationUri: sql.NullString{Valid: true, String: reg.URI}, }); updateErr != nil { - cfg.Logger.Warn("failed to persist registration URI", "error", updateErr) + logger.Warn("failed to persist registration URI", "error", updateErr) } } diff --git a/svc/ctrl/services/cluster/BUILD.bazel b/svc/ctrl/services/cluster/BUILD.bazel index 67a411cfe9..572149f2de 100644 --- a/svc/ctrl/services/cluster/BUILD.bazel +++ b/svc/ctrl/services/cluster/BUILD.bazel @@ -22,7 +22,7 @@ go_library( "//gen/proto/ctrl/v1/ctrlv1connect", "//pkg/assert", "//pkg/db", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/uid", "@com_connectrpc_connect//:connect", ], diff --git a/svc/ctrl/services/cluster/rpc_get_desired_deployment_state.go b/svc/ctrl/services/cluster/rpc_get_desired_deployment_state.go index 86677a70c1..7b502e89ae 100644 --- a/svc/ctrl/services/cluster/rpc_get_desired_deployment_state.go +++ b/svc/ctrl/services/cluster/rpc_get_desired_deployment_state.go @@ -8,6 +8,7 @@ import ( ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" "github.com/unkeyed/unkey/pkg/assert" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" ) // GetDesiredDeploymentState returns the target state for a single deployment in the caller's @@ -80,7 +81,7 @@ func (s *Service) GetDesiredDeploymentState(ctx context.Context, req *connect.Re }, }), nil default: - s.logger.Error("unhandled Deployment desired state", "desiredState", deployment.DesiredState) + logger.Error("unhandled Deployment desired state", "desiredState", deployment.DesiredState) } return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("unhandled Deployment desired state: %s", deployment.DesiredState)) diff --git a/svc/ctrl/services/cluster/rpc_get_desired_sentinel_state.go b/svc/ctrl/services/cluster/rpc_get_desired_sentinel_state.go index b40aca50b2..71647378ba 100644 --- a/svc/ctrl/services/cluster/rpc_get_desired_sentinel_state.go +++ b/svc/ctrl/services/cluster/rpc_get_desired_sentinel_state.go @@ -8,6 +8,7 @@ import ( ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" "github.com/unkeyed/unkey/pkg/assert" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" ) // GetDesiredSentinelState returns the target state for a single sentinel resource. This is @@ -42,7 +43,7 @@ func (s *Service) GetDesiredSentinelState(ctx context.Context, req *connect.Requ } - s.logger.Info("desired sentinel", "state", sentinel.DesiredState) + logger.Info("desired sentinel", "state", sentinel.DesiredState) switch sentinel.DesiredState { case db.SentinelsDesiredStateArchived, db.SentinelsDesiredStateStandby: return connect.NewResponse(&ctrlv1.SentinelState{ @@ -70,7 +71,7 @@ func (s *Service) GetDesiredSentinelState(ctx context.Context, req *connect.Requ }, }), nil default: - s.logger.Error("unhandled sentinel desired state", "desiredState", sentinel.DesiredState) + logger.Error("unhandled sentinel desired state", "desiredState", sentinel.DesiredState) } return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("unhandled sentinel desired state: %s", sentinel.DesiredState)) diff --git a/svc/ctrl/services/cluster/rpc_report_deployment_status.go b/svc/ctrl/services/cluster/rpc_report_deployment_status.go index 45334aa3ab..343a9938c5 100644 --- a/svc/ctrl/services/cluster/rpc_report_deployment_status.go +++ b/svc/ctrl/services/cluster/rpc_report_deployment_status.go @@ -7,6 +7,7 @@ import ( ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" "github.com/unkeyed/unkey/pkg/assert" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/uid" ) @@ -26,7 +27,7 @@ import ( // Returns CodeUnauthenticated if bearer token is invalid. Database errors during the // transaction are returned as-is (not wrapped in Connect error codes). func (s *Service) ReportDeploymentStatus(ctx context.Context, req *connect.Request[ctrlv1.ReportDeploymentStatusRequest]) (*connect.Response[ctrlv1.ReportDeploymentStatusResponse], error) { - s.logger.Info("reporting deployment status", "req", req.Msg) + logger.Info("reporting deployment status", "req", req.Msg) if err := s.authenticate(req); err != nil { return nil, err diff --git a/svc/ctrl/services/cluster/rpc_watch_cilium_network_policies.go b/svc/ctrl/services/cluster/rpc_watch_cilium_network_policies.go index 37f1cb3d55..354205cf80 100644 --- a/svc/ctrl/services/cluster/rpc_watch_cilium_network_policies.go +++ b/svc/ctrl/services/cluster/rpc_watch_cilium_network_policies.go @@ -8,6 +8,7 @@ import ( ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" "github.com/unkeyed/unkey/pkg/assert" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" ) // WatchCiliumNetworkPolicies streams Cilium network policy state changes from the control plane to agents. @@ -49,7 +50,7 @@ func (s *Service) WatchCiliumNetworkPolicies( states, err := s.fetchCiliumNetworkPolicyStates(ctx, region, versionCursor) if err != nil { - s.logger.Error("failed to fetch cilium network policy states", "error", err) + logger.Error("failed to fetch cilium network policy states", "error", err) return connect.NewError(connect.CodeInternal, err) } diff --git a/svc/ctrl/services/cluster/rpc_watch_deployments.go b/svc/ctrl/services/cluster/rpc_watch_deployments.go index a830a6d04b..291b1314b4 100644 --- a/svc/ctrl/services/cluster/rpc_watch_deployments.go +++ b/svc/ctrl/services/cluster/rpc_watch_deployments.go @@ -8,6 +8,7 @@ import ( ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" "github.com/unkeyed/unkey/pkg/assert" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" ) // WatchDeployments streams deployment state changes from the control plane to agents. @@ -50,7 +51,7 @@ func (s *Service) WatchDeployments( states, err := s.fetchDeploymentStates(ctx, region, versionCursor) if err != nil { - s.logger.Error("failed to fetch deployment states", "error", err) + logger.Error("failed to fetch deployment states", "error", err) return connect.NewError(connect.CodeInternal, err) } @@ -86,7 +87,7 @@ func (s *Service) fetchDeploymentStates(ctx context.Context, region string, afte for _, row := range rows { state, err := s.deploymentRowToState(row) if err != nil { - s.logger.Error("failed to convert deployment row to state", "error", err, "deploymentId", row.Deployment.ID) + logger.Error("failed to convert deployment row to state", "error", err, "deploymentId", row.Deployment.ID) continue } states = append(states, state) @@ -136,7 +137,7 @@ func (s *Service) deploymentRowToState(row db.ListDeploymentTopologyByRegionRow) }, }, nil default: - s.logger.Error("unhandled deployment topology desired status", "status", row.DeploymentTopology.DesiredStatus) + logger.Error("unhandled deployment topology desired status", "status", row.DeploymentTopology.DesiredStatus) return nil, nil } } diff --git a/svc/ctrl/services/cluster/rpc_watch_sentinels.go b/svc/ctrl/services/cluster/rpc_watch_sentinels.go index 5e1469a690..53178254d5 100644 --- a/svc/ctrl/services/cluster/rpc_watch_sentinels.go +++ b/svc/ctrl/services/cluster/rpc_watch_sentinels.go @@ -8,6 +8,7 @@ import ( ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" "github.com/unkeyed/unkey/pkg/assert" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" ) // WatchSentinels streams sentinel state changes from the control plane to agents. @@ -39,7 +40,7 @@ func (s *Service) WatchSentinels( } versionCursor := req.Msg.GetVersionLastSeen() - s.logger.Info("krane watching sentinels", + logger.Info("krane watching sentinels", "region", region, "version", versionCursor, ) @@ -53,7 +54,7 @@ func (s *Service) WatchSentinels( states, err := s.fetchSentinelStates(ctx, region, versionCursor) if err != nil { - s.logger.Error("failed to fetch sentinel states", "error", err) + logger.Error("failed to fetch sentinel states", "error", err) return connect.NewError(connect.CodeInternal, err) } @@ -128,7 +129,7 @@ func (s *Service) sentinelRowToState(sentinel db.Sentinel) *ctrlv1.SentinelState }, } default: - s.logger.Error("unhandled sentinel desired state", "desiredState", sentinel.DesiredState) + logger.Error("unhandled sentinel desired state", "desiredState", sentinel.DesiredState) return nil } } diff --git a/svc/ctrl/services/cluster/service.go b/svc/ctrl/services/cluster/service.go index 917e475248..380c84d76b 100644 --- a/svc/ctrl/services/cluster/service.go +++ b/svc/ctrl/services/cluster/service.go @@ -3,7 +3,6 @@ package cluster import ( "github.com/unkeyed/unkey/gen/proto/ctrl/v1/ctrlv1connect" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // Service implements [ctrlv1connect.ClusterServiceHandler] to synchronize desired state @@ -13,7 +12,6 @@ import ( type Service struct { ctrlv1connect.UnimplementedClusterServiceHandler db db.Database - logger logging.Logger bearer string } @@ -22,9 +20,6 @@ type Config struct { // Database provides read and write access for querying and updating resource state. Database db.Database - // Logger is used for structured logging throughout the service. - Logger logging.Logger - // Bearer is the authentication token that agents must provide in the Authorization header. Bearer string } @@ -35,7 +30,6 @@ func New(cfg Config) *Service { return &Service{ UnimplementedClusterServiceHandler: ctrlv1connect.UnimplementedClusterServiceHandler{}, db: cfg.Database, - logger: cfg.Logger, bearer: cfg.Bearer, } } diff --git a/svc/ctrl/services/customdomain/BUILD.bazel b/svc/ctrl/services/customdomain/BUILD.bazel index 8a3600663c..a6eb30780d 100644 --- a/svc/ctrl/services/customdomain/BUILD.bazel +++ b/svc/ctrl/services/customdomain/BUILD.bazel @@ -10,7 +10,7 @@ go_library( "//gen/proto/ctrl/v1/ctrlv1connect", "//gen/proto/hydra/v1:hydra", "//pkg/db", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/restate/admin", "//pkg/uid", "@com_connectrpc_connect//:connect", diff --git a/svc/ctrl/services/customdomain/service.go b/svc/ctrl/services/customdomain/service.go index a4d41ca100..e4f95020ed 100644 --- a/svc/ctrl/services/customdomain/service.go +++ b/svc/ctrl/services/customdomain/service.go @@ -13,7 +13,7 @@ import ( "github.com/unkeyed/unkey/gen/proto/ctrl/v1/ctrlv1connect" hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" restateadmin "github.com/unkeyed/unkey/pkg/restate/admin" "github.com/unkeyed/unkey/pkg/uid" ) @@ -26,7 +26,6 @@ type Service struct { db db.Database restate *restateingress.Client restateAdmin *restateadmin.Client - logger logging.Logger cnameDomain string } @@ -38,8 +37,6 @@ type Config struct { Restate *restateingress.Client // RestateAdmin is the admin client for canceling invocations. RestateAdmin *restateadmin.Client - // Logger is used for structured logging throughout the service. - Logger logging.Logger // CnameDomain is the base domain for custom domain CNAME targets. CnameDomain string } @@ -51,7 +48,6 @@ func New(cfg Config) *Service { db: cfg.Database, restate: cfg.Restate, restateAdmin: cfg.RestateAdmin, - logger: cfg.Logger, cnameDomain: cfg.CnameDomain, } } @@ -120,7 +116,7 @@ func (s *Service) AddCustomDomain( client := hydrav1.NewCustomDomainServiceIngressClient(s.restate, domain) sendResp, sendErr := client.VerifyDomain().Send(ctx, &hydrav1.VerifyDomainRequest{}) if sendErr != nil { - s.logger.Warn("failed to trigger verification workflow", + logger.Warn("failed to trigger verification workflow", "domain", domain, "error", sendErr, ) @@ -162,7 +158,7 @@ func (s *Service) DeleteCustomDomain( // Cancel any running verification workflow if domain.InvocationID.Valid && s.restateAdmin != nil { if cancelErr := s.restateAdmin.CancelInvocation(ctx, domain.InvocationID.String); cancelErr != nil { - s.logger.Warn("failed to cancel verification workflow", + logger.Warn("failed to cancel verification workflow", "domain", domain.Domain, "invocation_id", domain.InvocationID.String, "error", cancelErr, @@ -219,7 +215,7 @@ func (s *Service) RetryVerification( // Cancel any existing verification workflow if domain.InvocationID.Valid && s.restateAdmin != nil { if cancelErr := s.restateAdmin.CancelInvocation(ctx, domain.InvocationID.String); cancelErr != nil { - s.logger.Warn("failed to cancel old verification workflow", + logger.Warn("failed to cancel old verification workflow", "domain", domain.Domain, "invocation_id", domain.InvocationID.String, "error", cancelErr, diff --git a/svc/ctrl/services/deployment/BUILD.bazel b/svc/ctrl/services/deployment/BUILD.bazel index f997032433..d8350313eb 100644 --- a/svc/ctrl/services/deployment/BUILD.bazel +++ b/svc/ctrl/services/deployment/BUILD.bazel @@ -18,7 +18,7 @@ go_library( "//gen/proto/hydra/v1:hydra", "//pkg/db", "//pkg/db/types", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/uid", "@com_connectrpc_connect//:connect", "@com_github_restatedev_sdk_go//ingress", diff --git a/svc/ctrl/services/deployment/create_deployment.go b/svc/ctrl/services/deployment/create_deployment.go index bf10f150f0..e74343485e 100644 --- a/svc/ctrl/services/deployment/create_deployment.go +++ b/svc/ctrl/services/deployment/create_deployment.go @@ -12,6 +12,7 @@ import ( hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" dbtype "github.com/unkeyed/unkey/pkg/db/types" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/uid" "google.golang.org/protobuf/encoding/protojson" ) @@ -145,7 +146,7 @@ func (s *Service) CreateDeployment( gitCommitTimestamp = gitCommit.GetTimestamp() } - s.logger.Info("deployment will use prebuilt image", + logger.Info("deployment will use prebuilt image", "deployment_id", deploymentID, "image", dockerImage) @@ -183,11 +184,11 @@ func (s *Service) CreateDeployment( MemoryMib: 256, }) if err != nil { - s.logger.Error("failed to insert deployment", "error", err.Error()) + logger.Error("failed to insert deployment", "error", err.Error()) return nil, connect.NewError(connect.CodeInternal, err) } - s.logger.Info("starting deployment workflow", + logger.Info("starting deployment workflow", "deployment_id", deploymentID, "workspace_id", workspaceID, "project_id", req.Msg.GetProjectId(), @@ -218,11 +219,11 @@ func (s *Service) CreateDeployment( Deploy(). Send(ctx, deployReq) if err != nil { - s.logger.Error("failed to start deployment workflow", "error", err) + logger.Error("failed to start deployment workflow", "error", err) return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("unable to start workflow: %w", err)) } - s.logger.Info("deployment workflow started", + logger.Info("deployment workflow started", "deployment_id", deploymentID, "invocation_id", invocation.Id, ) diff --git a/svc/ctrl/services/deployment/doc.go b/svc/ctrl/services/deployment/doc.go index 0322860396..6e36b2aa51 100644 --- a/svc/ctrl/services/deployment/doc.go +++ b/svc/ctrl/services/deployment/doc.go @@ -45,7 +45,6 @@ // svc := deployment.New(deployment.Config{ // Database: db, // Restate: restateClient, -// Logger: logger, // AvailableRegions: []string{"us-east-1", "eu-west-1"}, // BuildStorage: s3Storage, // }) diff --git a/svc/ctrl/services/deployment/get_deployment.go b/svc/ctrl/services/deployment/get_deployment.go index 5b65a71fcd..aa6b5feef3 100644 --- a/svc/ctrl/services/deployment/get_deployment.go +++ b/svc/ctrl/services/deployment/get_deployment.go @@ -7,6 +7,7 @@ import ( "connectrpc.com/connect" ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" ) // GetDeployment retrieves a deployment by ID including its current status, @@ -24,7 +25,7 @@ func (s *Service) GetDeployment( if db.IsNotFound(err) { return nil, connect.NewError(connect.CodeNotFound, err) } - s.logger.Error("failed to load deployment", "error", err, "deployment_id", req.Msg.GetDeploymentId()) + logger.Error("failed to load deployment", "error", err, "deployment_id", req.Msg.GetDeploymentId()) return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("failed to load deployment")) } @@ -76,7 +77,7 @@ func (s *Service) GetDeployment( // Fetch routes (fqdns) for this deployment routes, err := db.Query.FindFrontlineRoutesByDeploymentID(ctx, s.db.RO(), req.Msg.GetDeploymentId()) if err != nil { - s.logger.Warn("failed to fetch frontline routes for deployment", "error", err, "deployment_id", deployment.ID) + logger.Warn("failed to fetch frontline routes for deployment", "error", err, "deployment_id", deployment.ID) // Continue without fqdns rather than failing the entire request } else { fqdns := make([]string, len(routes)) diff --git a/svc/ctrl/services/deployment/promote.go b/svc/ctrl/services/deployment/promote.go index 834154e2df..90a9e89cec 100644 --- a/svc/ctrl/services/deployment/promote.go +++ b/svc/ctrl/services/deployment/promote.go @@ -8,6 +8,7 @@ import ( ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" ) // Promote reassigns all domains to the target deployment via a Restate workflow. @@ -16,7 +17,7 @@ import ( // The workflow runs synchronously (blocking until complete) and is keyed by // project ID to prevent concurrent promotion operations on the same project. func (s *Service) Promote(ctx context.Context, req *connect.Request[ctrlv1.PromoteRequest]) (*connect.Response[ctrlv1.PromoteResponse], error) { - s.logger.Info("initiating promotion via Restate", + logger.Info("initiating promotion via Restate", "target", req.Msg.GetTargetDeploymentId(), ) @@ -26,7 +27,7 @@ func (s *Service) Promote(ctx context.Context, req *connect.Request[ctrlv1.Promo if db.IsNotFound(err) { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("deployment not found: %s", req.Msg.GetTargetDeploymentId())) } - s.logger.Error("failed to get deployment", + logger.Error("failed to get deployment", "deployment_id", req.Msg.GetTargetDeploymentId(), "error", err.Error(), ) @@ -42,14 +43,14 @@ func (s *Service) Promote(ctx context.Context, req *connect.Request[ctrlv1.Promo }) if err != nil { - s.logger.Error("promotion workflow failed", + logger.Error("promotion workflow failed", "target", req.Msg.GetTargetDeploymentId(), "error", err.Error(), ) return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("promotion workflow failed: %w", err)) } - s.logger.Info("promotion completed successfully via Restate", + logger.Info("promotion completed successfully via Restate", "target", req.Msg.GetTargetDeploymentId(), ) diff --git a/svc/ctrl/services/deployment/rollback.go b/svc/ctrl/services/deployment/rollback.go index a6d2a5e539..8b20ef3d9b 100644 --- a/svc/ctrl/services/deployment/rollback.go +++ b/svc/ctrl/services/deployment/rollback.go @@ -8,6 +8,7 @@ import ( ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" ) // Rollback switches traffic from the source deployment to a previous target @@ -16,7 +17,7 @@ import ( // (blocking until complete) and is keyed by project ID to prevent concurrent // rollback operations on the same project. func (s *Service) Rollback(ctx context.Context, req *connect.Request[ctrlv1.RollbackRequest]) (*connect.Response[ctrlv1.RollbackResponse], error) { - s.logger.Info("initiating rollback via Restate", + logger.Info("initiating rollback via Restate", "source", req.Msg.GetSourceDeploymentId(), "target", req.Msg.GetTargetDeploymentId(), ) @@ -27,7 +28,7 @@ func (s *Service) Rollback(ctx context.Context, req *connect.Request[ctrlv1.Roll if db.IsNotFound(err) { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("deployment not found: %s", req.Msg.GetSourceDeploymentId())) } - s.logger.Error("failed to get deployment", + logger.Error("failed to get deployment", "deployment_id", req.Msg.GetSourceDeploymentId(), "error", err.Error(), ) @@ -44,7 +45,7 @@ func (s *Service) Rollback(ctx context.Context, req *connect.Request[ctrlv1.Roll }) if err != nil { - s.logger.Error("rollback workflow failed", + logger.Error("rollback workflow failed", "source", req.Msg.GetSourceDeploymentId(), "target", req.Msg.GetTargetDeploymentId(), "error", err.Error(), @@ -52,7 +53,7 @@ func (s *Service) Rollback(ctx context.Context, req *connect.Request[ctrlv1.Roll return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("rollback workflow failed: %w", err)) } - s.logger.Info("rollback completed successfully via Restate", + logger.Info("rollback completed successfully via Restate", "source", req.Msg.GetSourceDeploymentId(), "target", req.Msg.GetTargetDeploymentId(), ) diff --git a/svc/ctrl/services/deployment/service.go b/svc/ctrl/services/deployment/service.go index 6240107001..3a0c438d7d 100644 --- a/svc/ctrl/services/deployment/service.go +++ b/svc/ctrl/services/deployment/service.go @@ -5,7 +5,6 @@ import ( "github.com/unkeyed/unkey/gen/proto/ctrl/v1/ctrlv1connect" hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // Service implements the DeploymentService ConnectRPC API. It coordinates @@ -15,7 +14,6 @@ type Service struct { ctrlv1connect.UnimplementedDeploymentServiceHandler db db.Database restate *restateingress.Client - logger logging.Logger availableRegions []string } @@ -31,8 +29,6 @@ type Config struct { Database db.Database // Restate is the ingress client for triggering durable workflows. Restate *restateingress.Client - // Logger is used for structured logging throughout the service. - Logger logging.Logger // AvailableRegions lists the regions where deployments can be created. AvailableRegions []string } @@ -44,7 +40,6 @@ func New(cfg Config) *Service { UnimplementedDeploymentServiceHandler: ctrlv1connect.UnimplementedDeploymentServiceHandler{}, db: cfg.Database, restate: cfg.Restate, - logger: cfg.Logger, availableRegions: cfg.AvailableRegions, } } diff --git a/svc/ctrl/services/doc.go b/svc/ctrl/services/doc.go index 6e70ba71d6..165ed42ff2 100644 --- a/svc/ctrl/services/doc.go +++ b/svc/ctrl/services/doc.go @@ -46,7 +46,7 @@ // Database: database, // Restate: restateClient, // BuildService: buildService, -// Logger: logger, +// , // }) // // // Register with Connect server diff --git a/svc/ctrl/services/openapi/BUILD.bazel b/svc/ctrl/services/openapi/BUILD.bazel index b7484470b0..0abeb02d19 100644 --- a/svc/ctrl/services/openapi/BUILD.bazel +++ b/svc/ctrl/services/openapi/BUILD.bazel @@ -16,7 +16,6 @@ go_library( "//gen/proto/ctrl/v1/ctrlv1connect", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", "//pkg/ptr", "@com_connectrpc_connect//:connect", "@com_github_getkin_kin_openapi//openapi3", diff --git a/svc/ctrl/services/openapi/service.go b/svc/ctrl/services/openapi/service.go index ae5a28e26a..da106a2f27 100644 --- a/svc/ctrl/services/openapi/service.go +++ b/svc/ctrl/services/openapi/service.go @@ -3,19 +3,16 @@ package openapi import ( "github.com/unkeyed/unkey/gen/proto/ctrl/v1/ctrlv1connect" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) type Service struct { ctrlv1connect.UnimplementedOpenApiServiceHandler - db db.Database - logger logging.Logger + db db.Database } -func New(database db.Database, logger logging.Logger) *Service { +func New(database db.Database) *Service { return &Service{ UnimplementedOpenApiServiceHandler: ctrlv1connect.UnimplementedOpenApiServiceHandler{}, db: database, - logger: logger, } } diff --git a/svc/ctrl/services/openapi/utils.go b/svc/ctrl/services/openapi/utils.go index a8a67ec974..677620e97b 100644 --- a/svc/ctrl/services/openapi/utils.go +++ b/svc/ctrl/services/openapi/utils.go @@ -13,7 +13,7 @@ func (s *Service) loadOpenApiSpec(ctx context.Context, deploymentID string) (str return "", err } - // Consider: s.logger.Debug("Deployment fetched", "id", deployment.ID, "hasSpec", deployment.OpenapiSpec.Valid) + // Consider: logger.Debug("Deployment fetched", "id", deployment.ID, "hasSpec", deployment.OpenapiSpec.Valid) if !deployment.OpenapiSpec.Valid { return "", fault.New("deployment has no OpenAPI spec stored", fault.Public("OpenAPI specification not available for this deployment"), diff --git a/svc/ctrl/worker/BUILD.bazel b/svc/ctrl/worker/BUILD.bazel index 0929905643..bad150779d 100644 --- a/svc/ctrl/worker/BUILD.bazel +++ b/svc/ctrl/worker/BUILD.bazel @@ -18,8 +18,8 @@ go_library( "//pkg/clock", "//pkg/db", "//pkg/healthcheck", + "//pkg/logger", "//pkg/otel", - "//pkg/otel/logging", "//pkg/prometheus", "//pkg/restate/admin", "//pkg/rpc/interceptor", diff --git a/svc/ctrl/worker/certificate/BUILD.bazel b/svc/ctrl/worker/certificate/BUILD.bazel index 66a2e302a3..c8452d7563 100644 --- a/svc/ctrl/worker/certificate/BUILD.bazel +++ b/svc/ctrl/worker/certificate/BUILD.bazel @@ -17,7 +17,7 @@ go_library( "//gen/proto/vault/v1/vaultv1connect", "//pkg/db", "//pkg/healthcheck", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/uid", "//svc/ctrl/services/acme", "@com_connectrpc_connect//:connect", diff --git a/svc/ctrl/worker/certificate/bootstrap_infra_certs.go b/svc/ctrl/worker/certificate/bootstrap_infra_certs.go index 8752639a67..713c61ef2f 100644 --- a/svc/ctrl/worker/certificate/bootstrap_infra_certs.go +++ b/svc/ctrl/worker/certificate/bootstrap_infra_certs.go @@ -9,6 +9,7 @@ import ( restateIngress "github.com/restatedev/sdk-go/ingress" hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/uid" ) @@ -53,7 +54,7 @@ type BootstrapConfig struct { // certs require DNS-01 challenges for wildcards. Logs a warning in this case. func (s *Service) BootstrapInfraCerts(ctx context.Context, cfg BootstrapConfig) error { if s.dnsProvider == nil { - s.logger.Warn("DNS provider not configured, skipping infrastructure cert bootstrap") + logger.Warn("DNS provider not configured, skipping infrastructure cert bootstrap") return nil } @@ -73,7 +74,7 @@ func (s *Service) BootstrapInfraCerts(ctx context.Context, cfg BootstrapConfig) } if len(domains) == 0 { - s.logger.Info("no infrastructure domains configured, skipping cert bootstrap") + logger.Info("no infrastructure domains configured, skipping cert bootstrap") return nil } @@ -97,7 +98,7 @@ func (s *Service) ensureInfraDomain(ctx context.Context, domain string, restate // If cert already exists, we're done if existingDomain.CertificateID.Valid && existingDomain.CertificateID.String != "" { - s.logger.Info("infrastructure cert already exists", "domain", domain, "cert_id", existingDomain.CertificateID.String) + logger.Info("infrastructure cert already exists", "domain", domain, "cert_id", existingDomain.CertificateID.String) return nil } @@ -138,12 +139,12 @@ func (s *Service) ensureInfraDomain(ctx context.Context, domain string, restate return fmt.Errorf("failed to create ACME challenge record: %w", err) } - s.logger.Info("created infrastructure domain records", "domain", domain, "domain_id", domainID) + logger.Info("created infrastructure domain records", "domain", domain, "domain_id", domainID) } // Trigger the ProcessChallenge workflow via Restate // Use domain as key so multiple domains can be processed in parallel - s.logger.Info("triggering certificate challenge workflow", "domain", domain) + logger.Info("triggering certificate challenge workflow", "domain", domain) certClient := hydrav1.NewCertificateServiceIngressClient(restate, domain) _, err = certClient.ProcessChallenge().Send(ctx, &hydrav1.ProcessChallengeRequest{ @@ -151,7 +152,7 @@ func (s *Service) ensureInfraDomain(ctx context.Context, domain string, restate Domain: domain, }) if err != nil { - s.logger.Warn("failed to trigger certificate workflow, renewal cron will retry", + logger.Warn("failed to trigger certificate workflow, renewal cron will retry", "domain", domain, "error", err, ) diff --git a/svc/ctrl/worker/certificate/process_challenge_handler.go b/svc/ctrl/worker/certificate/process_challenge_handler.go index 97477e0560..e01667ceee 100644 --- a/svc/ctrl/worker/certificate/process_challenge_handler.go +++ b/svc/ctrl/worker/certificate/process_challenge_handler.go @@ -13,6 +13,7 @@ import ( hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/svc/ctrl/services/acme" ) @@ -60,7 +61,7 @@ func (s *Service) ProcessChallenge( ctx restate.ObjectContext, req *hydrav1.ProcessChallengeRequest, ) (resp *hydrav1.ProcessChallengeResponse, err error) { - s.logger.Info("starting certificate challenge", + logger.Info("starting certificate challenge", "workspace_id", req.GetWorkspaceId(), "domain", req.GetDomain(), ) @@ -121,7 +122,7 @@ func (s *Service) ProcessChallenge( // Check if it's a rate limit error if rle, ok := acme.AsRateLimitError(obtainErr); ok { if rateLimitRetry >= maxRateLimitRetries { - s.logger.Error("max rate limit retries exceeded", + logger.Error("max rate limit retries exceeded", "domain", req.GetDomain(), "retries", rateLimitRetry, ) @@ -140,7 +141,7 @@ func (s *Service) ProcessChallenge( sleepDuration = 2 * time.Hour // cap at 2 hours } - s.logger.Info("rate limited, sleeping until retry-after", + logger.Info("rate limited, sleeping until retry-after", "domain", req.GetDomain(), "retry_after", rle.RetryAfter, "sleep_duration", sleepDuration, @@ -183,7 +184,7 @@ func (s *Service) ProcessChallenge( return nil, err } - s.logger.Info("certificate challenge completed successfully", + logger.Info("certificate challenge completed successfully", "domain", req.GetDomain(), "certificate_id", certID, "expires_at", cert.ExpiresAt, @@ -212,7 +213,6 @@ func (s *Service) getOrCreateAcmeClient(ctx context.Context, domain string) (*le // Use a single global ACME user for all certificates client, err := acme.GetOrCreateUser(ctx, acme.UserConfig{ DB: s.db, - Logger: s.logger, Vault: s.vault, WorkspaceID: globalAcmeUserID, EmailDomain: s.emailDomain, @@ -230,7 +230,7 @@ func (s *Service) getOrCreateAcmeClient(ctx context.Context, domain string) (*le if err := client.Challenge.SetDNS01Provider(s.dnsProvider); err != nil { return nil, fmt.Errorf("failed to set DNS-01 provider: %w", err) } - s.logger.Info("using DNS-01 challenge for wildcard domain", "domain", domain) + logger.Info("using DNS-01 challenge for wildcard domain", "domain", domain) } else { if s.httpProvider == nil { return nil, fmt.Errorf("HTTP provider required for certificate: %s", domain) @@ -238,7 +238,7 @@ func (s *Service) getOrCreateAcmeClient(ctx context.Context, domain string) (*le if err := client.Challenge.SetHTTP01Provider(s.httpProvider); err != nil { return nil, fmt.Errorf("failed to set HTTP-01 provider: %w", err) } - s.logger.Info("using HTTP-01 challenge for domain", "domain", domain) + logger.Info("using HTTP-01 challenge for domain", "domain", domain) } return client, nil @@ -246,12 +246,12 @@ func (s *Service) getOrCreateAcmeClient(ctx context.Context, domain string) (*le // obtainCertificate requests a certificate and encrypts the private key for storage. func (s *Service) obtainCertificate(ctx context.Context, _ string, dom db.CustomDomain, domain string) (EncryptedCertificate, error) { - s.logger.Info("creating ACME client", "domain", domain) + logger.Info("creating ACME client", "domain", domain) client, err := s.getOrCreateAcmeClient(ctx, domain) if err != nil { return EncryptedCertificate{}, fmt.Errorf("failed to create ACME client: %w", err) } - s.logger.Info("ACME client created, requesting certificate", "domain", domain) + logger.Info("ACME client created, requesting certificate", "domain", domain) // Request certificate from Let's Encrypt // Restate handles retries - we return TerminalError for non-retryable errors @@ -264,7 +264,7 @@ func (s *Service) obtainCertificate(ctx context.Context, _ string, dom db.Custom certificates, err := client.Certificate.Obtain(request) if err != nil { parsed := acme.ParseACMEError(err) - s.logger.Error("certificate obtain failed", + logger.Error("certificate obtain failed", "domain", domain, "error_type", parsed.Type, "message", parsed.Message, @@ -291,7 +291,7 @@ func (s *Service) obtainCertificate(ctx context.Context, _ string, dom db.Custom // Parse certificate to get expiration expiresAt, err := acme.GetCertificateExpiry(certificates.Certificate) if err != nil { - s.logger.Warn("failed to parse certificate expiry, using default", "error", err) + logger.Warn("failed to parse certificate expiry, using default", "error", err) expiresAt = time.Now().Add(90 * 24 * time.Hour).UnixMilli() } @@ -353,7 +353,7 @@ func (s *Service) markChallengeFailed(ctx restate.ObjectContext, domainID string Status: db.AcmeChallengesStatusFailed, UpdatedAt: sql.NullInt64{Valid: true, Int64: time.Now().UnixMilli()}, }); updateErr != nil { - s.logger.Error("failed to update challenge status", "error", updateErr, "domain_id", domainID) + logger.Error("failed to update challenge status", "error", updateErr, "domain_id", domainID) } return restate.Void{}, nil }, restate.WithName("mark failed")) diff --git a/svc/ctrl/worker/certificate/renew_handler.go b/svc/ctrl/worker/certificate/renew_handler.go index 2140d01787..b2aeb12e6e 100644 --- a/svc/ctrl/worker/certificate/renew_handler.go +++ b/svc/ctrl/worker/certificate/renew_handler.go @@ -7,6 +7,7 @@ import ( restate "github.com/restatedev/sdk-go" hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" ) // RenewExpiringCertificates renews certificates before they expire. @@ -22,7 +23,7 @@ func (s *Service) RenewExpiringCertificates( ctx restate.ObjectContext, req *hydrav1.RenewExpiringCertificatesRequest, ) (*hydrav1.RenewExpiringCertificatesResponse, error) { - s.logger.Info("starting certificate renewal check") + logger.Info("starting certificate renewal check") challengeTypes := []db.AcmeChallengesChallengeType{ db.AcmeChallengesChallengeTypeDNS01, @@ -37,13 +38,13 @@ func (s *Service) RenewExpiringCertificates( return nil, err } - s.logger.Info("found certificates to process", "count", len(challenges)) + logger.Info("found certificates to process", "count", len(challenges)) var failedDomains []string renewalsTriggered := int32(0) for _, challenge := range challenges { - s.logger.Info("triggering certificate renewal", + logger.Info("triggering certificate renewal", "domain", challenge.Domain, "workspace_id", challenge.WorkspaceID, ) @@ -56,7 +57,7 @@ func (s *Service) RenewExpiringCertificates( }) if sendErr != nil { - s.logger.Warn("failed to trigger renewal", + logger.Warn("failed to trigger renewal", "domain", challenge.Domain, "error", sendErr, ) @@ -71,7 +72,7 @@ func (s *Service) RenewExpiringCertificates( } } - s.logger.Info("certificate renewal check completed", + logger.Info("certificate renewal check completed", "checked", len(challenges), "triggered", renewalsTriggered, "failed", len(failedDomains), diff --git a/svc/ctrl/worker/certificate/service.go b/svc/ctrl/worker/certificate/service.go index 86a22140eb..9576d7e44e 100644 --- a/svc/ctrl/worker/certificate/service.go +++ b/svc/ctrl/worker/certificate/service.go @@ -6,7 +6,6 @@ import ( "github.com/unkeyed/unkey/gen/proto/vault/v1/vaultv1connect" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/healthcheck" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // Service orchestrates ACME certificate issuance and renewal. @@ -28,7 +27,6 @@ type Service struct { hydrav1.UnimplementedCertificateServiceServer db db.Database vault vaultv1connect.VaultServiceClient - logger logging.Logger emailDomain string defaultDomain string dnsProvider challenge.Provider @@ -47,9 +45,6 @@ type Config struct { // the workspace ID as the keyring identifier. Vault vaultv1connect.VaultServiceClient - // Logger receives structured log output from certificate operations. - Logger logging.Logger - // EmailDomain forms the email address for ACME account registration. The service // constructs emails as "acme@{EmailDomain}" for the global ACME account. EmailDomain string @@ -81,7 +76,6 @@ func New(cfg Config) *Service { UnimplementedCertificateServiceServer: hydrav1.UnimplementedCertificateServiceServer{}, db: cfg.DB, vault: cfg.Vault, - logger: cfg.Logger, emailDomain: cfg.EmailDomain, defaultDomain: cfg.DefaultDomain, dnsProvider: cfg.DNSProvider, diff --git a/svc/ctrl/worker/clickhouseuser/BUILD.bazel b/svc/ctrl/worker/clickhouseuser/BUILD.bazel index d946fa40d6..2c7a2d8402 100644 --- a/svc/ctrl/worker/clickhouseuser/BUILD.bazel +++ b/svc/ctrl/worker/clickhouseuser/BUILD.bazel @@ -15,7 +15,7 @@ go_library( "//gen/proto/vault/v1/vaultv1connect", "//pkg/clickhouse", "//pkg/db", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/ptr", "@com_connectrpc_connect//:connect", "@com_github_restatedev_sdk_go//:sdk-go", diff --git a/svc/ctrl/worker/clickhouseuser/configure_user_handler.go b/svc/ctrl/worker/clickhouseuser/configure_user_handler.go index bcf2051394..7e7de1bd4e 100644 --- a/svc/ctrl/worker/clickhouseuser/configure_user_handler.go +++ b/svc/ctrl/worker/clickhouseuser/configure_user_handler.go @@ -12,6 +12,7 @@ import ( vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" "github.com/unkeyed/unkey/pkg/clickhouse" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/ptr" ) @@ -61,7 +62,7 @@ func (s *Service) ConfigureUser( req *hydrav1.ConfigureUserRequest, ) (*hydrav1.ConfigureUserResponse, error) { workspaceID := restate.Key(ctx) - s.logger.Info("configuring clickhouse user", "workspace_id", workspaceID) + logger.Info("configuring clickhouse user", "workspace_id", workspaceID) quotas := resolveQuotaSettings(req) @@ -88,7 +89,7 @@ func (s *Service) ConfigureUser( var retentionDays int32 if !result.Found { - s.logger.Info("creating new user", "workspace_id", workspaceID) + logger.Info("creating new user", "workspace_id", workspaceID) // Fetch retention days from workspace quota quota, err := restate.Run(ctx, func(rc restate.RunContext) (db.Quotum, error) { @@ -166,7 +167,7 @@ func (s *Service) ConfigureUser( } } else { - s.logger.Info("updating existing user", "workspace_id", workspaceID) + logger.Info("updating existing user", "workspace_id", workspaceID) retentionDays = result.Row.Quotas.LogsRetentionDays encryptedPassword = result.Row.ClickhouseWorkspaceSetting.PasswordEncrypted @@ -216,7 +217,7 @@ func (s *Service) ConfigureUser( return nil, fmt.Errorf("configure clickhouse: %w", err) } - s.logger.Info("configured clickhouse user", "workspace_id", workspaceID, "retention_days", retentionDays) + logger.Info("configured clickhouse user", "workspace_id", workspaceID, "retention_days", retentionDays) return &hydrav1.ConfigureUserResponse{}, nil } diff --git a/svc/ctrl/worker/clickhouseuser/service.go b/svc/ctrl/worker/clickhouseuser/service.go index a8e1984b43..e22e6920b7 100644 --- a/svc/ctrl/worker/clickhouseuser/service.go +++ b/svc/ctrl/worker/clickhouseuser/service.go @@ -5,7 +5,6 @@ import ( "github.com/unkeyed/unkey/gen/proto/vault/v1/vaultv1connect" "github.com/unkeyed/unkey/pkg/clickhouse" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // Service orchestrates ClickHouse user provisioning for workspaces. @@ -22,7 +21,6 @@ type Service struct { db db.Database vault vaultv1connect.VaultServiceClient clickhouse clickhouse.ClickHouse - logger logging.Logger } var _ hydrav1.ClickhouseUserServiceServer = (*Service)(nil) @@ -40,9 +38,6 @@ type Config struct { // Must be connected as a user with CREATE/ALTER/DROP permissions for USER, QUOTA, // ROW POLICY, and SETTINGS PROFILE, plus GRANT OPTION on analytics tables. Clickhouse clickhouse.ClickHouse - - // Logger receives structured log output from user provisioning operations. - Logger logging.Logger } // New creates a [Service] with the given configuration. The returned service is @@ -53,6 +48,5 @@ func New(cfg Config) *Service { db: cfg.DB, vault: cfg.Vault, clickhouse: cfg.Clickhouse, - logger: cfg.Logger, } } diff --git a/svc/ctrl/worker/customdomain/BUILD.bazel b/svc/ctrl/worker/customdomain/BUILD.bazel index 645ec09d4a..f19749f33f 100644 --- a/svc/ctrl/worker/customdomain/BUILD.bazel +++ b/svc/ctrl/worker/customdomain/BUILD.bazel @@ -14,7 +14,7 @@ go_library( "//pkg/db", "//pkg/dns", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/uid", "@com_github_restatedev_sdk_go//:sdk-go", ], diff --git a/svc/ctrl/worker/customdomain/doc.go b/svc/ctrl/worker/customdomain/doc.go index c48c2be70b..f9e50f7adf 100644 --- a/svc/ctrl/worker/customdomain/doc.go +++ b/svc/ctrl/worker/customdomain/doc.go @@ -38,7 +38,6 @@ // // svc := customdomain.New(customdomain.Config{ // DB: database, -// Logger: logger, // CnameDomain: "unkey-dns.com", // }) // diff --git a/svc/ctrl/worker/customdomain/service.go b/svc/ctrl/worker/customdomain/service.go index fe850f83c2..1a3e15cfde 100644 --- a/svc/ctrl/worker/customdomain/service.go +++ b/svc/ctrl/worker/customdomain/service.go @@ -3,7 +3,6 @@ package customdomain import ( hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // Service orchestrates custom domain verification workflows. @@ -22,7 +21,6 @@ import ( type Service struct { hydrav1.UnimplementedCustomDomainServiceServer db db.Database - logger logging.Logger cnameDomain string } @@ -33,9 +31,6 @@ type Config struct { // DB provides database access for custom domain records. DB db.Database - // Logger receives structured log output from domain verification operations. - Logger logging.Logger - // CnameDomain is the base domain for custom domain CNAME targets. // Each custom domain gets a unique subdomain like "{random}.{CnameDomain}". // For production: "unkey-dns.com" @@ -48,7 +43,6 @@ func New(cfg Config) *Service { return &Service{ UnimplementedCustomDomainServiceServer: hydrav1.UnimplementedCustomDomainServiceServer{}, db: cfg.DB, - logger: cfg.Logger, cnameDomain: cfg.CnameDomain, } } diff --git a/svc/ctrl/worker/customdomain/verify_handler.go b/svc/ctrl/worker/customdomain/verify_handler.go index 770a6f80e3..bdf7efb47f 100644 --- a/svc/ctrl/worker/customdomain/verify_handler.go +++ b/svc/ctrl/worker/customdomain/verify_handler.go @@ -13,6 +13,7 @@ import ( "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/dns" "github.com/unkeyed/unkey/pkg/fault" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/uid" ) @@ -87,14 +88,14 @@ func (s *Service) VerifyDomain( cnameResult := <-cnameCh if txtResult.err != nil { - s.logger.Warn("TXT check error", + logger.Warn("TXT check error", "domain", dom.Domain, "error", txtResult.err, "elapsed", elapsed, ) } if cnameResult.err != nil { - s.logger.Warn("CNAME check error", + logger.Warn("CNAME check error", "domain", dom.Domain, "error", cnameResult.err, "elapsed", elapsed, @@ -126,7 +127,7 @@ func (s *Service) VerifyDomain( } // Log current status - s.logger.Info("DNS verification check complete", + logger.Info("DNS verification check complete", "domain", dom.Domain, "txt_verified", txtVerified, "cname_verified", cnameVerified, @@ -150,7 +151,7 @@ func (s *Service) RetryVerification( _ *hydrav1.RetryVerificationRequest, ) (*hydrav1.RetryVerificationResponse, error) { domain := restate.Key(ctx) - s.logger.Info("retrying domain verification", "domain", domain) + logger.Info("retrying domain verification", "domain", domain) _, err := restate.Run(ctx, func(stepCtx restate.RunContext) (restate.Void, error) { return restate.Void{}, db.Query.ResetCustomDomainVerification(stepCtx, s.db.RW(), db.ResetCustomDomainVerificationParams{ @@ -291,7 +292,7 @@ func (s *Service) onVerificationSuccess( return nil, fault.Wrap(err, fault.Internal("failed to create frontline route")) } - s.logger.Info("domain verification completed successfully", + logger.Info("domain verification completed successfully", "domain", dom.Domain, ) @@ -317,7 +318,7 @@ func (s *Service) onVerificationFailed( return nil, fault.Wrap(err, fault.Internal("failed to mark domain as failed")) } - s.logger.Info("domain verification failed", + logger.Info("domain verification failed", "domain", dom.Domain, "error", errorMsg, ) diff --git a/svc/ctrl/worker/deploy/BUILD.bazel b/svc/ctrl/worker/deploy/BUILD.bazel index e06ffec381..72238c359a 100644 --- a/svc/ctrl/worker/deploy/BUILD.bazel +++ b/svc/ctrl/worker/deploy/BUILD.bazel @@ -23,7 +23,7 @@ go_library( "//pkg/clickhouse", "//pkg/clickhouse/schema", "//pkg/db", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/ptr", "//pkg/uid", "//svc/ctrl/worker/github", diff --git a/svc/ctrl/worker/deploy/build.go b/svc/ctrl/worker/deploy/build.go index a617dc25f2..d42130eba1 100644 --- a/svc/ctrl/worker/deploy/build.go +++ b/svc/ctrl/worker/deploy/build.go @@ -25,6 +25,7 @@ import ( "github.com/unkeyed/unkey/pkg/clickhouse/schema" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/ptr" ) @@ -72,7 +73,7 @@ func (w *Workflow) buildDockerImageFromGit( platform := w.buildPlatform.Platform architecture := w.buildPlatform.Architecture - w.logger.Info("Starting git build process", + logger.Info("Starting git build process", "repository", params.Repository, "commit_sha", params.CommitSHA, "project_id", params.ProjectID, @@ -86,7 +87,7 @@ func (w *Workflow) buildDockerImageFromGit( return nil, fmt.Errorf("failed to get/create depot project: %w", err) } - w.logger.Info("Creating depot build", + logger.Info("Creating depot build", "depot_project_id", depotProjectID, "project_id", params.ProjectID) @@ -106,12 +107,12 @@ func (w *Workflow) buildDockerImageFromGit( } defer func() { depotBuild.Finish(err) }() - w.logger.Info("Depot build created", + logger.Info("Depot build created", "build_id", depotBuild.ID, "depot_project_id", depotProjectID, "project_id", params.ProjectID) - w.logger.Info("Acquiring build machine", + logger.Info("Acquiring build machine", "build_id", depotBuild.ID, "architecture", architecture, "project_id", params.ProjectID) @@ -122,11 +123,11 @@ func (w *Workflow) buildDockerImageFromGit( } defer func() { if releaseErr := buildkit.Release(); releaseErr != nil { - w.logger.Error("unable to release buildkit", "error", releaseErr) + logger.Error("unable to release buildkit", "error", releaseErr) } }() - w.logger.Info("Build machine acquired, connecting to buildkit", + logger.Info("Build machine acquired, connecting to buildkit", "build_id", depotBuild.ID, "project_id", params.ProjectID) @@ -136,7 +137,7 @@ func (w *Workflow) buildDockerImageFromGit( } defer func() { if closeErr := buildClient.Close(); closeErr != nil { - w.logger.Error("unable to close client", "error", closeErr) + logger.Error("unable to close client", "error", closeErr) } }() @@ -162,7 +163,7 @@ func (w *Workflow) buildDockerImageFromGit( gitContextURL = fmt.Sprintf("https://github.com/%s.git#%s:%s", params.Repository, params.CommitSHA, contextPath) } - w.logger.Info("Starting build execution", + logger.Info("Starting build execution", "image_name", imageName, "dockerfile", dockerfilePath, "platform", platform, @@ -182,7 +183,7 @@ func (w *Workflow) buildDockerImageFromGit( return nil, fmt.Errorf("build failed: %w", err) } - w.logger.Info("Build completed successfully") + logger.Info("Build completed successfully") return &buildResult{ ImageName: imageName, @@ -287,7 +288,7 @@ func (w *Workflow) getOrCreateDepotProject(ctx context.Context, unkeyProjectID s projectName := fmt.Sprintf("unkey-%s", unkeyProjectID) if project.DepotProjectID.Valid && project.DepotProjectID.String != "" { - w.logger.Info( + logger.Info( "Returning existing depot project", "depot_project_id", project.DepotProjectID, "project_id", unkeyProjectID, @@ -333,7 +334,7 @@ func (w *Workflow) getOrCreateDepotProject(ctx context.Context, unkeyProjectID s return "", fmt.Errorf("failed to update depot_project_id: %w", err) } - w.logger.Info("Created new Depot project", + logger.Info("Created new Depot project", "depot_project_id", depotProjectID, "project_id", unkeyProjectID, "project_name", projectName) @@ -357,7 +358,7 @@ func (w *Workflow) processBuildStatus( for _, vertex := range status.Vertexes { if vertex == nil { - w.logger.Warn("vertex is nil") + logger.Warn("vertex is nil") continue } if vertex.Completed != nil && !completed[vertex.Digest] { diff --git a/svc/ctrl/worker/deploy/deploy_handler.go b/svc/ctrl/worker/deploy/deploy_handler.go index 6a6025d16b..a2056e9324 100644 --- a/svc/ctrl/worker/deploy/deploy_handler.go +++ b/svc/ctrl/worker/deploy/deploy_handler.go @@ -12,6 +12,7 @@ import ( hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/assert" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/uid" ) @@ -62,7 +63,7 @@ func (w *Workflow) Deploy(ctx restate.WorkflowSharedContext, req *hydrav1.Deploy return nil, restate.TerminalError(err) } - w.logger.Info("deployment workflow started", "req", fmt.Sprintf("%+v", req)) + logger.Info("deployment workflow started", "req", fmt.Sprintf("%+v", req)) deployment, err := restate.Run(ctx, func(runCtx restate.RunContext) (db.Deployment, error) { return db.Query.FindDeploymentById(runCtx, w.db.RW(), req.GetDeploymentId()) @@ -77,7 +78,7 @@ func (w *Workflow) Deploy(ctx restate.WorkflowSharedContext, req *hydrav1.Deploy } if err = w.updateDeploymentStatus(ctx, deployment.ID, db.DeploymentsStatusFailed); err != nil { - w.logger.Error("deployment failed but we can not set the status", "error", err.Error()) + logger.Error("deployment failed but we can not set the status", "error", err.Error()) } }() workspace, err := restate.Run(ctx, func(runCtx restate.RunContext) (db.Workspace, error) { @@ -272,7 +273,7 @@ func (w *Workflow) Deploy(ctx restate.WorkflowSharedContext, req *hydrav1.Deploy if err := w.ensureCiliumNetworkPolicy(ctx, workspace, project, environment, topologies); err != nil { return nil, err } - w.logger.Info("waiting for deployments to be ready", "deployment_id", deployment.ID) + logger.Info("waiting for deployments to be ready", "deployment_id", deployment.ID) readygates := make([]restate.Future, len(topologies)) for i, region := range topologies { @@ -314,7 +315,7 @@ func (w *Workflow) Deploy(ctx restate.WorkflowSharedContext, req *hydrav1.Deploy } } - w.logger.Info("deployments ready", "deployment_id", deployment.ID) + logger.Info("deployments ready", "deployment_id", deployment.ID) allDomains := buildDomains( workspace.Slug, @@ -409,7 +410,7 @@ func (w *Workflow) Deploy(ctx restate.WorkflowSharedContext, req *hydrav1.Deploy } } - w.logger.Info("deployment workflow completed", + logger.Info("deployment workflow completed", "deployment_id", deployment.ID, "status", "succeeded", "domains", len(allDomains), diff --git a/svc/ctrl/worker/deploy/doc.go b/svc/ctrl/worker/deploy/doc.go index 96c76fd10b..4817276fec 100644 --- a/svc/ctrl/worker/deploy/doc.go +++ b/svc/ctrl/worker/deploy/doc.go @@ -36,7 +36,6 @@ // workflow := deploy.New(deploy.Config{ // DB: mainDB, // Krane: kraneClient, -// Logger: logger, // DefaultDomain: "unkey.app", // }) // diff --git a/svc/ctrl/worker/deploy/promote_handler.go b/svc/ctrl/worker/deploy/promote_handler.go index 62fb4d353a..7fb2f145e9 100644 --- a/svc/ctrl/worker/deploy/promote_handler.go +++ b/svc/ctrl/worker/deploy/promote_handler.go @@ -8,6 +8,7 @@ import ( restate "github.com/restatedev/sdk-go" hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" ) // Promote reassigns all sticky domains to a deployment and clears the rolled back state. @@ -29,7 +30,7 @@ import ( // Returns terminal errors (400/404) for validation failures and retryable errors // for system failures. func (w *Workflow) Promote(ctx restate.WorkflowSharedContext, req *hydrav1.PromoteRequest) (*hydrav1.PromoteResponse, error) { - w.logger.Info("initiating promotion", "target", req.GetTargetDeploymentId()) + logger.Info("initiating promotion", "target", req.GetTargetDeploymentId()) // Get target deployment targetDeployment, err := restate.Run(ctx, func(stepCtx restate.RunContext) (db.Deployment, error) { @@ -82,7 +83,7 @@ func (w *Workflow) Promote(ctx restate.WorkflowSharedContext, req *hydrav1.Promo return nil, restate.TerminalError(fmt.Errorf("no frontlineRoutes found for promotion"), 400) } - w.logger.Info("found frontlineRoutes for promotion", "count", len(frontlineRoutes), "deployment_id", targetDeployment.ID) + logger.Info("found frontlineRoutes for promotion", "count", len(frontlineRoutes), "deployment_id", targetDeployment.ID) // Collect domain IDs var routeIDs []string @@ -111,14 +112,14 @@ func (w *Workflow) Promote(ctx restate.WorkflowSharedContext, req *hydrav1.Promo if err != nil { return restate.Void{}, fmt.Errorf("failed to update project's live deployment id: %w", err) } - w.logger.Info("updated project live deployment", "project_id", project.ID, "live_deployment_id", targetDeployment.ID) + logger.Info("updated project live deployment", "project_id", project.ID, "live_deployment_id", targetDeployment.ID) return restate.Void{}, nil }, restate.WithName("updating project live deployment")) if err != nil { return nil, err } - w.logger.Info("promotion completed successfully", + logger.Info("promotion completed successfully", "target", req.GetTargetDeploymentId(), "domains_promoted", len(routeIDs)) diff --git a/svc/ctrl/worker/deploy/rollback_handler.go b/svc/ctrl/worker/deploy/rollback_handler.go index a4185a4262..b3fed0ffee 100644 --- a/svc/ctrl/worker/deploy/rollback_handler.go +++ b/svc/ctrl/worker/deploy/rollback_handler.go @@ -8,6 +8,7 @@ import ( restate "github.com/restatedev/sdk-go" hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" ) // Rollback performs a rollback to a previous deployment. @@ -29,7 +30,7 @@ import ( // Returns terminal errors (400/404) for validation failures and retryable errors // for system failures. func (w *Workflow) Rollback(ctx restate.WorkflowSharedContext, req *hydrav1.RollbackRequest) (*hydrav1.RollbackResponse, error) { - w.logger.Info("initiating rollback", + logger.Info("initiating rollback", "source", req.GetSourceDeploymentId(), "target", req.GetTargetDeploymentId(), ) @@ -104,7 +105,7 @@ func (w *Workflow) Rollback(ctx restate.WorkflowSharedContext, req *hydrav1.Roll return nil, restate.TerminalError(fmt.Errorf("no frontlineRoutes to rollback"), 400) } - w.logger.Info("found frontlineRoutes for rollback", "count", len(frontlineRoutes), "deployment_id", sourceDeployment.ID) + logger.Info("found frontlineRoutes for rollback", "count", len(frontlineRoutes), "deployment_id", sourceDeployment.ID) // Collect frontlineRoute IDs var routeIDs []string @@ -136,14 +137,14 @@ func (w *Workflow) Rollback(ctx restate.WorkflowSharedContext, req *hydrav1.Roll if err != nil { return restate.Void{}, fmt.Errorf("failed to update project's live deployment id: %w", err) } - w.logger.Info("updated project live deployment", "project_id", project.ID, "live_deployment_id", targetDeployment.ID) + logger.Info("updated project live deployment", "project_id", project.ID, "live_deployment_id", targetDeployment.ID) return restate.Void{}, nil }, restate.WithName("updating project live deployment")) if err != nil { return nil, err } - w.logger.Info("rollback completed successfully", + logger.Info("rollback completed successfully", "source", req.GetSourceDeploymentId(), "target", req.GetTargetDeploymentId(), "frontlineRoutes_rolled_back", len(routeIDs)) diff --git a/svc/ctrl/worker/deploy/service.go b/svc/ctrl/worker/deploy/service.go index 283cda9c4e..0b7e0602a2 100644 --- a/svc/ctrl/worker/deploy/service.go +++ b/svc/ctrl/worker/deploy/service.go @@ -5,7 +5,6 @@ import ( "github.com/unkeyed/unkey/gen/proto/vault/v1/vaultv1connect" "github.com/unkeyed/unkey/pkg/clickhouse" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" githubclient "github.com/unkeyed/unkey/svc/ctrl/worker/github" ) @@ -40,8 +39,7 @@ type RegistryConfig struct { // concurrent deploy/rollback/promote operations. type Workflow struct { hydrav1.UnimplementedDeploymentServiceServer - db db.Database - logger logging.Logger + db db.Database defaultDomain string vault vaultv1connect.VaultServiceClient @@ -60,9 +58,6 @@ var _ hydrav1.DeploymentServiceServer = (*Workflow)(nil) // Config holds the configuration for creating a deployment workflow. type Config struct { - // Logger for structured logging. - Logger logging.Logger - // DB is the main database connection for workspace, project, and deployment data. DB db.Database @@ -99,7 +94,6 @@ func New(cfg Config) *Workflow { return &Workflow{ UnimplementedDeploymentServiceServer: hydrav1.UnimplementedDeploymentServiceServer{}, db: cfg.DB, - logger: cfg.Logger, defaultDomain: cfg.DefaultDomain, vault: cfg.Vault, sentinelImage: cfg.SentinelImage, diff --git a/svc/ctrl/worker/github/BUILD.bazel b/svc/ctrl/worker/github/BUILD.bazel index 0882981739..feb8849956 100644 --- a/svc/ctrl/worker/github/BUILD.bazel +++ b/svc/ctrl/worker/github/BUILD.bazel @@ -16,6 +16,6 @@ go_library( "//pkg/clock", "//pkg/fault", "//pkg/jwt", - "//pkg/otel/logging", + "//pkg/logger", ], ) diff --git a/svc/ctrl/worker/github/client.go b/svc/ctrl/worker/github/client.go index 3a762e45bd..ba960c8fbb 100644 --- a/svc/ctrl/worker/github/client.go +++ b/svc/ctrl/worker/github/client.go @@ -17,7 +17,7 @@ import ( "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/fault" "github.com/unkeyed/unkey/pkg/jwt" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) // ClientConfig holds configuration for creating a [Client] instance. @@ -45,13 +45,12 @@ type Client struct { config ClientConfig httpClient *http.Client signer jwt.Signer[jwt.RegisteredClaims] - logger logging.Logger tokenCache cache.Cache[int64, InstallationToken] } // NewClient creates a [Client] with the given configuration. Returns an error if // the private key cannot be parsed for JWT signing. -func NewClient(config ClientConfig, logger logging.Logger) (*Client, error) { +func NewClient(config ClientConfig) (*Client, error) { signer, err := jwt.NewRS256Signer[jwt.RegisteredClaims](config.PrivateKeyPEM) if err != nil { return nil, fault.Wrap(err, fault.Internal("failed to create JWT signer")) @@ -61,7 +60,6 @@ func NewClient(config ClientConfig, logger logging.Logger) (*Client, error) { Fresh: 55 * time.Minute, Stale: 5 * time.Minute, MaxSize: 10_000, - Logger: logger, Resource: "github_installation_token", Clock: clock.New(), }) @@ -73,7 +71,6 @@ func NewClient(config ClientConfig, logger logging.Logger) (*Client, error) { config: config, httpClient: &http.Client{Timeout: 30 * time.Second}, signer: signer, - logger: logger, tokenCache: tokenCache, }, nil } @@ -103,7 +100,7 @@ func (c *Client) GetInstallationToken(installationID int64) (InstallationToken, context.Background(), installationID, func(ctx context.Context) (InstallationToken, error) { - c.logger.Info( + logger.Info( "Getting GitHub installation token", "installation_id", installationID, ) diff --git a/svc/ctrl/worker/quotacheck/BUILD.bazel b/svc/ctrl/worker/quotacheck/BUILD.bazel index b0730795d3..165ca5d196 100644 --- a/svc/ctrl/worker/quotacheck/BUILD.bazel +++ b/svc/ctrl/worker/quotacheck/BUILD.bazel @@ -15,7 +15,7 @@ go_library( "//pkg/clickhouse", "//pkg/db", "//pkg/healthcheck", - "//pkg/otel/logging", + "//pkg/logger", "//svc/ctrl/internal/slack", "@com_github_restatedev_sdk_go//:sdk-go", "@org_golang_x_text//language", diff --git a/svc/ctrl/worker/quotacheck/run_check_handler.go b/svc/ctrl/worker/quotacheck/run_check_handler.go index 3b589e69ed..fbc992c4b4 100644 --- a/svc/ctrl/worker/quotacheck/run_check_handler.go +++ b/svc/ctrl/worker/quotacheck/run_check_handler.go @@ -10,6 +10,7 @@ import ( restate "github.com/restatedev/sdk-go" hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/svc/ctrl/internal/slack" "golang.org/x/text/language" "golang.org/x/text/message" @@ -46,7 +47,7 @@ func (s *Service) RunCheck( req *hydrav1.RunCheckRequest, ) (*hydrav1.RunCheckResponse, error) { billingPeriod := restate.Key(ctx) - s.logger.Info("running quota check", "billing_period", billingPeriod) + logger.Info("running quota check", "billing_period", billingPeriod) // Parse billing period to get year/month year, month, err := parseBillingPeriod(billingPeriod) @@ -81,7 +82,7 @@ func (s *Service) RunCheck( return nil, fmt.Errorf("failed to get billable usage: %w", err) } - s.logger.Info("fetched usage data", "workspaces_above_threshold", len(usageAboveThreshold)) + logger.Info("fetched usage data", "workspaces_above_threshold", len(usageAboveThreshold)) // Extract workspace IDs from the usage map workspaceIDs := make([]string, 0, len(usageAboveThreshold)) @@ -108,7 +109,7 @@ func (s *Service) RunCheck( for _, ws := range batch { workspacesChecked++ if workspacesChecked%1000 == 0 { - s.logger.Info("progress", "count", workspacesChecked) + logger.Info("progress", "count", workspacesChecked) } if !ws.Enabled { @@ -166,7 +167,7 @@ func (s *Service) RunCheck( restate.Set(ctx, stateKeyNotifiedWorkspaces, notifiedAt) } - s.logger.Info("quota check complete", + logger.Info("quota check complete", "billing_period", billingPeriod, "workspaces_checked", workspacesChecked, "workspaces_exceeded", len(exceeded), diff --git a/svc/ctrl/worker/quotacheck/service.go b/svc/ctrl/worker/quotacheck/service.go index f02bc54045..a6d157fdcc 100644 --- a/svc/ctrl/worker/quotacheck/service.go +++ b/svc/ctrl/worker/quotacheck/service.go @@ -6,7 +6,6 @@ import ( "github.com/unkeyed/unkey/pkg/clickhouse" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/healthcheck" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // Service implements the QuotaCheckService Restate virtual object. @@ -14,7 +13,6 @@ type Service struct { hydrav1.UnimplementedQuotaCheckServiceServer db db.Database clickhouse clickhouse.ClickHouse - logger logging.Logger heartbeat healthcheck.Heartbeat slackWebhookURL string } @@ -25,7 +23,6 @@ var _ hydrav1.QuotaCheckServiceServer = (*Service)(nil) type Config struct { DB db.Database Clickhouse clickhouse.ClickHouse - Logger logging.Logger // Heartbeat sends health signals after successful quota check runs. // Must not be nil - use healthcheck.NewNoop() if monitoring is not needed. Heartbeat healthcheck.Heartbeat @@ -44,7 +41,6 @@ func New(cfg Config) (*Service, error) { UnimplementedQuotaCheckServiceServer: hydrav1.UnimplementedQuotaCheckServiceServer{}, db: cfg.DB, clickhouse: cfg.Clickhouse, - logger: cfg.Logger, heartbeat: cfg.Heartbeat, slackWebhookURL: cfg.SlackWebhookURL, }, nil diff --git a/svc/ctrl/worker/routing/BUILD.bazel b/svc/ctrl/worker/routing/BUILD.bazel index 1aa7e499a1..3eca0f7b09 100644 --- a/svc/ctrl/worker/routing/BUILD.bazel +++ b/svc/ctrl/worker/routing/BUILD.bazel @@ -12,7 +12,7 @@ go_library( deps = [ "//gen/proto/hydra/v1:hydra", "//pkg/db", - "//pkg/otel/logging", + "//pkg/logger", "@com_github_restatedev_sdk_go//:sdk-go", ], ) diff --git a/svc/ctrl/worker/routing/assign_domains_handler.go b/svc/ctrl/worker/routing/assign_domains_handler.go index 0cd2ccb55c..b2763b95c5 100644 --- a/svc/ctrl/worker/routing/assign_domains_handler.go +++ b/svc/ctrl/worker/routing/assign_domains_handler.go @@ -8,6 +8,7 @@ import ( restate "github.com/restatedev/sdk-go" hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" ) // AssignFrontlineRoutes reassigns a set of frontline routes to a new deployment. @@ -20,7 +21,7 @@ import ( // Returns an empty response on success. Database errors from the route updates // propagate directly to the caller. func (s *Service) AssignFrontlineRoutes(ctx restate.ObjectContext, req *hydrav1.AssignFrontlineRoutesRequest) (*hydrav1.AssignFrontlineRoutesResponse, error) { - s.logger.Info("assigning domains", + logger.Info("assigning domains", "deployment_id", req.GetDeploymentId(), "frontline_route_count", len(req.GetFrontlineRouteIds()), ) diff --git a/svc/ctrl/worker/routing/doc.go b/svc/ctrl/worker/routing/doc.go index be709e7743..57744f25f1 100644 --- a/svc/ctrl/worker/routing/doc.go +++ b/svc/ctrl/worker/routing/doc.go @@ -30,7 +30,6 @@ // // routingSvc := routing.New(routing.Config{ // DB: mainDB, -// Logger: logger, // DefaultDomain: "unkey.app", // }) // diff --git a/svc/ctrl/worker/routing/service.go b/svc/ctrl/worker/routing/service.go index e82533d592..231b5cc99e 100644 --- a/svc/ctrl/worker/routing/service.go +++ b/svc/ctrl/worker/routing/service.go @@ -3,7 +3,6 @@ package routing import ( hydrav1 "github.com/unkeyed/unkey/gen/proto/hydra/v1" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // Service implements the routing service for frontline route management. @@ -14,7 +13,6 @@ import ( type Service struct { hydrav1.UnimplementedRoutingServiceServer db db.Database - logger logging.Logger defaultDomain string } @@ -22,8 +20,6 @@ var _ hydrav1.RoutingServiceServer = (*Service)(nil) // Config holds the configuration for creating a [Service]. type Config struct { - // Logger receives structured log output from routing operations. - Logger logging.Logger // DB provides access to frontline route records. DB db.Database // DefaultDomain is the apex domain for generated deployment URLs. @@ -35,7 +31,6 @@ func New(cfg Config) *Service { return &Service{ UnimplementedRoutingServiceServer: hydrav1.UnimplementedRoutingServiceServer{}, db: cfg.DB, - logger: cfg.Logger, defaultDomain: cfg.DefaultDomain, } } diff --git a/svc/ctrl/worker/run.go b/svc/ctrl/worker/run.go index 86623b1001..8b8835491d 100644 --- a/svc/ctrl/worker/run.go +++ b/svc/ctrl/worker/run.go @@ -21,8 +21,8 @@ import ( "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/healthcheck" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/prometheus" restateadmin "github.com/unkeyed/unkey/pkg/restate/admin" "github.com/unkeyed/unkey/pkg/rpc/interceptor" @@ -87,18 +87,14 @@ func Run(ctx context.Context, cfg Config) error { } } - logger := logging.New() - if cfg.InstanceID != "" { - logger = logger.With(slog.String("instanceID", cfg.InstanceID)) - } - if cfg.Region != "" { - logger = logger.With(slog.String("region", cfg.Region)) - } - if version.Version != "" { - logger = logger.With(slog.String("version", version.Version)) - } + // Add base attributes to global logger + logger.AddBaseAttrs(slog.GroupAttrs("instance", + slog.String("id", cfg.InstanceID), + slog.String("region", cfg.Region), + slog.String("version", version.Version), + )) - r := runner.New(logger) + r := runner.New() defer r.Recover() r.DeferCtx(shutdownGrafana) @@ -120,7 +116,6 @@ func Run(ctx context.Context, cfg Config) error { database, err := db.New(db.Config{ PrimaryDSN: cfg.DatabasePrimary, ReadOnlyDSN: "", - Logger: logger, }) if err != nil { return fmt.Errorf("unable to create db: %w", err) @@ -135,7 +130,7 @@ func Run(ctx context.Context, cfg Config) error { AppID: cfg.GitHub.AppID, PrivateKeyPEM: cfg.GitHub.PrivateKeyPEM, WebhookSecret: "", - }, logger) + }) if ghErr != nil { return fmt.Errorf("failed to create GitHub client: %w", ghErr) } @@ -148,8 +143,7 @@ func Run(ctx context.Context, cfg Config) error { var ch clickhouse.ClickHouse = clickhouse.NewNoop() if cfg.ClickhouseURL != "" { chClient, chErr := clickhouse.New(clickhouse.Config{ - URL: cfg.ClickhouseURL, - Logger: logger, + URL: cfg.ClickhouseURL, }) if chErr != nil { logger.Error("failed to create clickhouse client, continuing with noop", "error", chErr) @@ -158,11 +152,10 @@ func Run(ctx context.Context, cfg Config) error { } } - // Restate Server - restateSrv := restateServer.NewRestate().WithLogger(logging.Handler(), false) + // Restate Server - uses logging.GetHandler() for slog integration + restateSrv := restateServer.NewRestate().WithLogger(logger.GetHandler(), false) restateSrv.Bind(hydrav1.NewDeploymentServiceServer(deploy.New(deploy.Config{ - Logger: logger, DB: database, DefaultDomain: cfg.DefaultDomain, Vault: vaultClient, @@ -176,7 +169,6 @@ func Run(ctx context.Context, cfg Config) error { }))) restateSrv.Bind(hydrav1.NewRoutingServiceServer(routing.New(routing.Config{ - Logger: logger, DB: database, DefaultDomain: cfg.DefaultDomain, }), restate.WithIngressPrivate(true))) @@ -185,7 +177,6 @@ func Run(ctx context.Context, cfg Config) error { restateSrv.Bind(hydrav1.NewCustomDomainServiceServer(workercustomdomain.New(workercustomdomain.Config{ DB: database, - Logger: logger, CnameDomain: cfg.CnameDomain, }), // Retry every 1 minute for up to 24 hours (1440 attempts) @@ -207,7 +198,6 @@ func Run(ctx context.Context, cfg Config) error { Fresh: 5 * time.Minute, Stale: 10 * time.Minute, MaxSize: 10000, - Logger: logger, Resource: "domains", Clock: clk, }) @@ -222,7 +212,6 @@ func Run(ctx context.Context, cfg Config) error { // HTTP-01 provider for regular (non-wildcard) domains httpProv, httpErr := providers.NewHTTPProvider(providers.HTTPConfig{ DB: database, - Logger: logger, DomainCache: domainCache, }) if httpErr != nil { @@ -235,7 +224,6 @@ func Run(ctx context.Context, cfg Config) error { if cfg.Acme.Route53.Enabled { r53Provider, r53Err := providers.NewRoute53Provider(providers.Route53Config{ DB: database, - Logger: logger, AccessKeyID: cfg.Acme.Route53.AccessKeyID, SecretAccessKey: cfg.Acme.Route53.SecretAccessKey, Region: cfg.Acme.Route53.Region, @@ -257,7 +245,6 @@ func Run(ctx context.Context, cfg Config) error { certHeartbeat = healthcheck.NewChecklyHeartbeat(cfg.CertRenewalHeartbeatURL) } restateSrv.Bind(hydrav1.NewCertificateServiceServer(certificate.New(certificate.Config{ - Logger: logger, DB: database, Vault: vaultClient, EmailDomain: cfg.Acme.EmailDomain, @@ -274,8 +261,7 @@ func Run(ctx context.Context, cfg Config) error { logger.Warn("ClickhouseUserService disabled: vault not configured") } else { chAdmin, chAdminErr := clickhouse.New(clickhouse.Config{ - URL: cfg.ClickhouseAdminURL, - Logger: logger, + URL: cfg.ClickhouseAdminURL, }) if chAdminErr != nil { logger.Warn("ClickhouseUserService disabled: failed to connect to admin", @@ -286,7 +272,6 @@ func Run(ctx context.Context, cfg Config) error { DB: database, Vault: vaultClient, Clickhouse: chAdmin, - Logger: logger, }))) logger.Info("ClickhouseUserService enabled") } @@ -300,7 +285,6 @@ func Run(ctx context.Context, cfg Config) error { quotaCheckSvc, err := quotacheck.New(quotacheck.Config{ DB: database, Clickhouse: ch, - Logger: logger, Heartbeat: quotaHeartbeat, SlackWebhookURL: cfg.QuotaCheckSlackWebhookURL, }) @@ -375,9 +359,7 @@ func Run(ctx context.Context, cfg Config) error { } if cfg.PrometheusPort > 0 { - prom, promErr := prometheus.New(prometheus.Config{ - Logger: logger, - }) + prom, promErr := prometheus.New() if promErr != nil { return fmt.Errorf("failed to create prometheus server: %w", promErr) } diff --git a/svc/frontline/BUILD.bazel b/svc/frontline/BUILD.bazel index ca5f7aa3c7..f0544ab1ed 100644 --- a/svc/frontline/BUILD.bazel +++ b/svc/frontline/BUILD.bazel @@ -13,8 +13,8 @@ go_library( "//gen/proto/vault/v1/vaultv1connect", "//pkg/clock", "//pkg/db", + "//pkg/logger", "//pkg/otel", - "//pkg/otel/logging", "//pkg/prometheus", "//pkg/ptr", "//pkg/rpc/interceptor", diff --git a/svc/frontline/config.go b/svc/frontline/config.go index 77b6514805..3fd289dcf6 100644 --- a/svc/frontline/config.go +++ b/svc/frontline/config.go @@ -1,5 +1,7 @@ package frontline +import "time" + type Config struct { // FrontlineID is the unique identifier for this instance of the Frontline server FrontlineID string @@ -70,6 +72,14 @@ type Config struct { // VaultToken is the authentication token for the vault service VaultToken string + + // --- Logging sampler configuration --- + + // LogSampleRate is the baseline probability (0.0-1.0) of emitting log events. + LogSampleRate float64 + + // LogSlowThreshold defines what duration qualifies as "slow" for sampling. + LogSlowThreshold time.Duration } func (c Config) Validate() error { diff --git a/svc/frontline/middleware/BUILD.bazel b/svc/frontline/middleware/BUILD.bazel index fbff7e303c..c2158be8cf 100644 --- a/svc/frontline/middleware/BUILD.bazel +++ b/svc/frontline/middleware/BUILD.bazel @@ -8,7 +8,7 @@ go_library( deps = [ "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/otel/tracing", "//pkg/zen", "@com_github_prometheus_client_golang//prometheus", diff --git a/svc/frontline/middleware/observability.go b/svc/frontline/middleware/observability.go index 8314296421..9c8ac1685c 100644 --- a/svc/frontline/middleware/observability.go +++ b/svc/frontline/middleware/observability.go @@ -13,7 +13,7 @@ import ( "github.com/prometheus/client_golang/prometheus/promauto" "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" "github.com/unkeyed/unkey/pkg/zen" "go.opentelemetry.io/otel/attribute" @@ -102,7 +102,7 @@ func categorizeErrorTypeFrontline(urn codes.URN, statusCode int, hasError bool) return "unknown" } -func WithObservability(logger logging.Logger, region string) zen.Middleware { +func WithObservability(region string) zen.Middleware { return func(next zen.HandleFunc) zen.HandleFunc { return func(ctx context.Context, s *zen.Session) error { startTime := time.Now() diff --git a/svc/frontline/routes/BUILD.bazel b/svc/frontline/routes/BUILD.bazel index a66b1983a6..9033a3e7d9 100644 --- a/svc/frontline/routes/BUILD.bazel +++ b/svc/frontline/routes/BUILD.bazel @@ -11,7 +11,6 @@ go_library( deps = [ "//gen/proto/ctrl/v1/ctrlv1connect", "//pkg/clock", - "//pkg/otel/logging", "//pkg/zen", "//svc/frontline/middleware", "//svc/frontline/routes/acme", diff --git a/svc/frontline/routes/acme/BUILD.bazel b/svc/frontline/routes/acme/BUILD.bazel index cb210faf0e..1d81209c0d 100644 --- a/svc/frontline/routes/acme/BUILD.bazel +++ b/svc/frontline/routes/acme/BUILD.bazel @@ -10,7 +10,7 @@ go_library( "//gen/proto/ctrl/v1/ctrlv1connect", "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/zen", "//svc/frontline/services/proxy", "//svc/frontline/services/router", diff --git a/svc/frontline/routes/acme/handler.go b/svc/frontline/routes/acme/handler.go index 28b3b431ae..10ba4223bf 100644 --- a/svc/frontline/routes/acme/handler.go +++ b/svc/frontline/routes/acme/handler.go @@ -10,14 +10,13 @@ import ( "github.com/unkeyed/unkey/gen/proto/ctrl/v1/ctrlv1connect" "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/frontline/services/proxy" "github.com/unkeyed/unkey/svc/frontline/services/router" ) type Handler struct { - Logger logging.Logger AcmeClient ctrlv1connect.AcmeServiceClient RouterService router.Service } @@ -43,7 +42,7 @@ func (h *Handler) Handle(ctx context.Context, sess *zen.Session) error { // Extract ACME token from path (last segment after /.well-known/acme-challenge/) token := path.Base(req.URL.Path) - h.Logger.Info("Handling ACME challenge", "hostname", hostname, "token", token) + logger.Info("Handling ACME challenge", "hostname", hostname, "token", token) createReq := connect.NewRequest(&ctrlv1.VerifyCertificateRequest{ Domain: hostname, Token: token, @@ -51,7 +50,7 @@ func (h *Handler) Handle(ctx context.Context, sess *zen.Session) error { resp, err := h.AcmeClient.VerifyCertificate(ctx, createReq) if err != nil { - h.Logger.Error("Failed to handle certificate verification", "error", err) + logger.Error("Failed to handle certificate verification", "error", err) return fault.Wrap(err, fault.Code(codes.App.Internal.UnexpectedError.URN()), fault.Internal("failed to handle ACME challenge"), @@ -60,6 +59,6 @@ func (h *Handler) Handle(ctx context.Context, sess *zen.Session) error { } auth := resp.Msg.GetAuthorization() - h.Logger.Info("Certificate verification handled", "response", auth) + logger.Info("Certificate verification handled", "response", auth) return sess.Plain(http.StatusOK, []byte(auth)) } diff --git a/svc/frontline/routes/internal_health/BUILD.bazel b/svc/frontline/routes/internal_health/BUILD.bazel index f5bb0edcb2..3cdf6124ec 100644 --- a/svc/frontline/routes/internal_health/BUILD.bazel +++ b/svc/frontline/routes/internal_health/BUILD.bazel @@ -5,8 +5,5 @@ go_library( srcs = ["handler.go"], importpath = "github.com/unkeyed/unkey/svc/frontline/routes/internal_health", visibility = ["//visibility:public"], - deps = [ - "//pkg/otel/logging", - "//pkg/zen", - ], + deps = ["//pkg/zen"], ) diff --git a/svc/frontline/routes/internal_health/handler.go b/svc/frontline/routes/internal_health/handler.go index 3b8fb421f6..2598fb9898 100644 --- a/svc/frontline/routes/internal_health/handler.go +++ b/svc/frontline/routes/internal_health/handler.go @@ -3,13 +3,10 @@ package handler import ( "context" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/zen" ) -type Handler struct { - Logger logging.Logger -} +type Handler struct{} func (h *Handler) Method() string { return "GET" diff --git a/svc/frontline/routes/proxy/BUILD.bazel b/svc/frontline/routes/proxy/BUILD.bazel index fa2ddc503e..0404d7973f 100644 --- a/svc/frontline/routes/proxy/BUILD.bazel +++ b/svc/frontline/routes/proxy/BUILD.bazel @@ -7,7 +7,6 @@ go_library( visibility = ["//visibility:public"], deps = [ "//pkg/clock", - "//pkg/otel/logging", "//pkg/zen", "//svc/frontline/services/proxy", "//svc/frontline/services/router", diff --git a/svc/frontline/routes/proxy/handler.go b/svc/frontline/routes/proxy/handler.go index 76acaaeff6..fc8d67be3e 100644 --- a/svc/frontline/routes/proxy/handler.go +++ b/svc/frontline/routes/proxy/handler.go @@ -4,14 +4,12 @@ import ( "context" "github.com/unkeyed/unkey/pkg/clock" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/frontline/services/proxy" "github.com/unkeyed/unkey/svc/frontline/services/router" ) type Handler struct { - Logger logging.Logger Region string RouterService router.Service ProxyService proxy.Service diff --git a/svc/frontline/routes/register.go b/svc/frontline/routes/register.go index d6785c9c94..a15eb54962 100644 --- a/svc/frontline/routes/register.go +++ b/svc/frontline/routes/register.go @@ -12,9 +12,9 @@ import ( // Register registers all frontline routes for the HTTPS server func Register(srv *zen.Server, svc *Services) { - withLogging := zen.WithLogging(svc.Logger) - withPanicRecovery := zen.WithPanicRecovery(svc.Logger) - withObservability := middleware.WithObservability(svc.Logger, svc.Region) + withLogging := zen.WithLogging() + withPanicRecovery := zen.WithPanicRecovery() + withObservability := middleware.WithObservability(svc.Region) withTimeout := zen.WithTimeout(5 * time.Minute) defaultMiddlewares := []zen.Middleware{ @@ -26,16 +26,13 @@ func Register(srv *zen.Server, svc *Services) { srv.RegisterRoute( []zen.Middleware{withLogging}, - &internalHealth.Handler{ - Logger: svc.Logger, - }, + &internalHealth.Handler{}, ) // Catches all requests and routes them to the sentinel or some other region. srv.RegisterRoute( defaultMiddlewares, &proxy.Handler{ - Logger: svc.Logger, Region: svc.Region, RouterService: svc.RouterService, ProxyService: svc.ProxyService, @@ -46,25 +43,22 @@ func Register(srv *zen.Server, svc *Services) { // RegisterChallengeServer registers routes for the HTTP challenge server (Let's Encrypt ACME) func RegisterChallengeServer(srv *zen.Server, svc *Services) { - withLogging := zen.WithLogging(svc.Logger) + withLogging := zen.WithLogging() // Health check endpoint srv.RegisterRoute( []zen.Middleware{withLogging}, - &internalHealth.Handler{ - Logger: svc.Logger, - }, + &internalHealth.Handler{}, ) // Catches /.well-known/acme-challenge/{token} so we can forward to ctrl plane. srv.RegisterRoute( []zen.Middleware{ - zen.WithPanicRecovery(svc.Logger), + zen.WithPanicRecovery(), withLogging, - middleware.WithObservability(svc.Logger, svc.Region), + middleware.WithObservability(svc.Region), }, &acme.Handler{ - Logger: svc.Logger, RouterService: svc.RouterService, AcmeClient: svc.AcmeClient, }, diff --git a/svc/frontline/routes/services.go b/svc/frontline/routes/services.go index 8dbaa5cbef..7f030973fa 100644 --- a/svc/frontline/routes/services.go +++ b/svc/frontline/routes/services.go @@ -3,13 +3,11 @@ package routes import ( "github.com/unkeyed/unkey/gen/proto/ctrl/v1/ctrlv1connect" "github.com/unkeyed/unkey/pkg/clock" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/svc/frontline/services/proxy" "github.com/unkeyed/unkey/svc/frontline/services/router" ) type Services struct { - Logger logging.Logger Region string RouterService router.Service ProxyService proxy.Service diff --git a/svc/frontline/run.go b/svc/frontline/run.go index e5607dd9fa..fa2c3504be 100644 --- a/svc/frontline/run.go +++ b/svc/frontline/run.go @@ -15,8 +15,8 @@ import ( "github.com/unkeyed/unkey/gen/proto/vault/v1/vaultv1connect" "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/prometheus" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/pkg/rpc/interceptor" @@ -43,6 +43,11 @@ func Run(ctx context.Context, cfg Config) error { return fmt.Errorf("bad config: %w", err) } + logger.SetSampler(logger.TailSampler{ + SlowThreshold: cfg.LogSlowThreshold, + SampleRate: cfg.LogSampleRate, + }) + // Create cached clock with millisecond resolution for efficient time tracking clk := clock.New() @@ -61,29 +66,26 @@ func Run(ctx context.Context, cfg Config) error { } } - // Create logger after InitGrafana so it picks up the OTLP handler - logger := logging.New() + // Configure global logger with base attributes if cfg.FrontlineID != "" { - logger = logger.With(slog.String("instanceID", cfg.FrontlineID)) + logger.AddBaseAttrs(slog.String("instanceID", cfg.FrontlineID)) } if cfg.Region != "" { - logger = logger.With(slog.String("region", cfg.Region)) + logger.AddBaseAttrs(slog.String("region", cfg.Region)) } if version.Version != "" { - logger = logger.With(slog.String("version", version.Version)) + logger.AddBaseAttrs(slog.String("version", version.Version)) } - r := runner.New(logger) + r := runner.New() defer r.Recover() r.DeferCtx(shutdownGrafana) if cfg.PrometheusPort > 0 { - prom, promErr := prometheus.New(prometheus.Config{ - Logger: logger, - }) + prom, promErr := prometheus.New() if promErr != nil { return fmt.Errorf("unable to start prometheus: %w", promErr) } @@ -120,7 +122,6 @@ func Run(ctx context.Context, cfg Config) error { db, err := db.New(db.Config{ PrimaryDSN: cfg.DatabasePrimary, ReadOnlyDSN: cfg.DatabaseReadonlyReplica, - Logger: logger, }) if err != nil { return fmt.Errorf("unable to create partitioned db: %w", err) @@ -129,8 +130,7 @@ func Run(ctx context.Context, cfg Config) error { // Initialize caches cache, err := caches.New(caches.Config{ - Logger: logger, - Clock: clk, + Clock: clk, }) if err != nil { return fmt.Errorf("unable to create caches: %w", err) @@ -140,7 +140,6 @@ func Run(ctx context.Context, cfg Config) error { var certManager certmanager.Service if vaultClient != nil { certManager = certmanager.New(certmanager.Config{ - Logger: logger, DB: db, TLSCertificateCache: cache.TLSCertificates, Vault: vaultClient, @@ -149,7 +148,6 @@ func Run(ctx context.Context, cfg Config) error { // Initialize router service routerSvc, err := router.New(router.Config{ - Logger: logger, Region: cfg.Region, DB: db, FrontlineRouteCache: cache.FrontlineRoutes, @@ -162,7 +160,6 @@ func Run(ctx context.Context, cfg Config) error { // Initialize proxy service with shared transport for connection pooling // nolint:exhaustruct proxySvc, err := proxy.New(proxy.Config{ - Logger: logger, FrontlineID: cfg.FrontlineID, Region: cfg.Region, ApexDomain: cfg.ApexDomain, @@ -208,7 +205,6 @@ func Run(ctx context.Context, cfg Config) error { acmeClient := ctrlv1connect.NewAcmeServiceClient(ptr.P(http.Client{}), cfg.CtrlAddr) svcs := &routes.Services{ - Logger: logger, Region: cfg.Region, RouterService: routerSvc, ProxyService: proxySvc, @@ -219,8 +215,7 @@ func Run(ctx context.Context, cfg Config) error { // Start HTTPS frontline server (main proxy server) if cfg.HttpsPort > 0 { httpsSrv, httpsErr := zen.New(zen.Config{ - Logger: logger, - TLS: tlsConfig, + TLS: tlsConfig, // Use longer timeouts for proxy operations // WriteTimeout must be longer than the transport's ResponseHeaderTimeout (30s) // so that transport timeouts can be caught and handled properly in ErrorHandler @@ -257,7 +252,6 @@ func Run(ctx context.Context, cfg Config) error { // Start HTTP challenge server (ACME only for Let's Encrypt) if cfg.HttpPort > 0 { httpSrv, httpErr := zen.New(zen.Config{ - Logger: logger, TLS: nil, Flags: nil, EnableH2C: false, diff --git a/svc/frontline/services/caches/BUILD.bazel b/svc/frontline/services/caches/BUILD.bazel index 4290bc64d4..a5f7e4783b 100644 --- a/svc/frontline/services/caches/BUILD.bazel +++ b/svc/frontline/services/caches/BUILD.bazel @@ -10,6 +10,5 @@ go_library( "//pkg/cache/middleware", "//pkg/clock", "//pkg/db", - "//pkg/otel/logging", ], ) diff --git a/svc/frontline/services/caches/caches.go b/svc/frontline/services/caches/caches.go index dfe8aa334b..2edfa6f900 100644 --- a/svc/frontline/services/caches/caches.go +++ b/svc/frontline/services/caches/caches.go @@ -9,7 +9,6 @@ import ( "github.com/unkeyed/unkey/pkg/cache/middleware" "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // Caches holds all cache instances used throughout frontline. @@ -26,15 +25,13 @@ type Caches struct { // Config defines the configuration options for initializing caches. type Config struct { - Logger logging.Logger - Clock clock.Clock + Clock clock.Clock } func New(config Config) (Caches, error) { frontlineRoute, err := cache.New(cache.Config[string, db.FrontlineRoute]{ Fresh: 30 * time.Second, Stale: 5 * time.Minute, - Logger: config.Logger, MaxSize: 10_000, Resource: "frontline_route", Clock: config.Clock, @@ -46,7 +43,6 @@ func New(config Config) (Caches, error) { sentinelsByEnvironment, err := cache.New(cache.Config[string, []db.Sentinel]{ Fresh: 30 * time.Second, Stale: 2 * time.Minute, - Logger: config.Logger, MaxSize: 10_000, Resource: "sentinels_by_environment", Clock: config.Clock, @@ -58,7 +54,6 @@ func New(config Config) (Caches, error) { tlsCertificate, err := cache.New(cache.Config[string, tls.Certificate]{ Fresh: time.Hour, Stale: time.Hour * 12, - Logger: config.Logger, MaxSize: 10_000, Resource: "tls_certificate", Clock: config.Clock, diff --git a/svc/frontline/services/certmanager/BUILD.bazel b/svc/frontline/services/certmanager/BUILD.bazel index faa25e315f..01911497ab 100644 --- a/svc/frontline/services/certmanager/BUILD.bazel +++ b/svc/frontline/services/certmanager/BUILD.bazel @@ -15,7 +15,7 @@ go_library( "//internal/services/caches", "//pkg/cache", "//pkg/db", - "//pkg/otel/logging", + "//pkg/logger", "@com_connectrpc_connect//:connect", ], ) diff --git a/svc/frontline/services/certmanager/interface.go b/svc/frontline/services/certmanager/interface.go index 009c81f092..4632b9d598 100644 --- a/svc/frontline/services/certmanager/interface.go +++ b/svc/frontline/services/certmanager/interface.go @@ -7,7 +7,6 @@ import ( "github.com/unkeyed/unkey/gen/proto/vault/v1/vaultv1connect" "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) type Service interface { @@ -16,8 +15,6 @@ type Service interface { } type Config struct { - Logger logging.Logger - DB db.Database Vault vaultv1connect.VaultServiceClient diff --git a/svc/frontline/services/certmanager/service.go b/svc/frontline/services/certmanager/service.go index 565575e287..0a71d129b7 100644 --- a/svc/frontline/services/certmanager/service.go +++ b/svc/frontline/services/certmanager/service.go @@ -13,15 +13,13 @@ import ( "github.com/unkeyed/unkey/internal/services/caches" "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) var _ Service = (*service)(nil) // service provides a basic certificate manager. type service struct { - logger logging.Logger - db db.Database vault vaultv1connect.VaultServiceClient @@ -32,10 +30,9 @@ type service struct { // New creates a new certificate manager. func New(cfg Config) *service { return &service{ - logger: cfg.Logger, - db: cfg.DB, - cache: cfg.TLSCertificateCache, - vault: cfg.Vault, + db: cfg.DB, + cache: cfg.TLSCertificateCache, + vault: cfg.Vault, } } @@ -91,7 +88,7 @@ func (s *service) GetCertificate(ctx context.Context, domain string) (*tls.Certi }, caches.DefaultFindFirstOp) if err != nil && !db.IsNotFound(err) { - s.logger.Error("Failed to get certificate", "error", err) + logger.Error("Failed to get certificate", "error", err) return nil, err } diff --git a/svc/frontline/services/proxy/BUILD.bazel b/svc/frontline/services/proxy/BUILD.bazel index 57483a44d2..11a8451438 100644 --- a/svc/frontline/services/proxy/BUILD.bazel +++ b/svc/frontline/services/proxy/BUILD.bazel @@ -20,7 +20,7 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/timing", "//pkg/zen", "@org_golang_x_net//http2", diff --git a/svc/frontline/services/proxy/director.go b/svc/frontline/services/proxy/director.go index 6d1e49de50..e193f72491 100644 --- a/svc/frontline/services/proxy/director.go +++ b/svc/frontline/services/proxy/director.go @@ -5,6 +5,7 @@ import ( "strconv" "time" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/timing" "github.com/unkeyed/unkey/pkg/zen" ) @@ -68,7 +69,7 @@ func (s *service) makeRegionDirector(sess *zen.Session, startTime time.Time) fun req.Header.Set(HeaderFrontlineHops, strconv.Itoa(currentHops)) if currentHops >= s.maxHops-1 { - s.logger.Warn("approaching max hops limit", + logger.Warn("approaching max hops limit", "currentHops", currentHops, "maxHops", s.maxHops, "hostname", req.Host, diff --git a/svc/frontline/services/proxy/forward.go b/svc/frontline/services/proxy/forward.go index 3173a6edd8..868ad28a1f 100644 --- a/svc/frontline/services/proxy/forward.go +++ b/svc/frontline/services/proxy/forward.go @@ -9,6 +9,7 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/timing" "github.com/unkeyed/unkey/pkg/zen" ) @@ -109,7 +110,7 @@ func (s *service) forward(sess *zen.Session, cfg forwardConfig) error { if ecw, ok := w.(*zen.ErrorCapturingWriter); ok { ecw.SetError(err) - s.logger.Warn(fmt.Sprintf("proxy error forwarding to %s", cfg.logTarget), + logger.Warn(fmt.Sprintf("proxy error forwarding to %s", cfg.logTarget), "error", err.Error(), "target", cfg.targetURL.String(), "hostname", r.Host, diff --git a/svc/frontline/services/proxy/interface.go b/svc/frontline/services/proxy/interface.go index 97ba635743..3a4fabbaf2 100644 --- a/svc/frontline/services/proxy/interface.go +++ b/svc/frontline/services/proxy/interface.go @@ -7,7 +7,6 @@ import ( "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/zen" ) @@ -26,9 +25,6 @@ type Service interface { // Config holds configuration for the proxy service. type Config struct { - // Logger for debugging and monitoring - Logger logging.Logger - // FrontlineID is the current frontline instance ID FrontlineID string diff --git a/svc/frontline/services/proxy/service.go b/svc/frontline/services/proxy/service.go index 53a96e88e2..cf029c2f5e 100644 --- a/svc/frontline/services/proxy/service.go +++ b/svc/frontline/services/proxy/service.go @@ -14,13 +14,12 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/zen" "golang.org/x/net/http2" ) type service struct { - logger logging.Logger frontlineID string region string apexDomain string @@ -96,7 +95,6 @@ func New(cfg Config) (*service, error) { } return &service{ - logger: cfg.Logger, frontlineID: cfg.FrontlineID, region: cfg.Region, apexDomain: cfg.ApexDomain, @@ -132,7 +130,7 @@ func (s *service) ForwardToRegion(ctx context.Context, sess *zen.Session, target if hopCountStr := sess.Request().Header.Get(HeaderFrontlineHops); hopCountStr != "" { if hops, err := strconv.Atoi(hopCountStr); err == nil && hops >= s.maxHops { - s.logger.Error("too many frontline hops - rejecting request", + logger.Error("too many frontline hops - rejecting request", "hops", hops, "maxHops", s.maxHops, "hostname", sess.Request().Host, diff --git a/svc/frontline/services/router/BUILD.bazel b/svc/frontline/services/router/BUILD.bazel index 534314c013..680c7cf2dc 100644 --- a/svc/frontline/services/router/BUILD.bazel +++ b/svc/frontline/services/router/BUILD.bazel @@ -15,6 +15,5 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", ], ) diff --git a/svc/frontline/services/router/interface.go b/svc/frontline/services/router/interface.go index c270437450..f0ddf504ec 100644 --- a/svc/frontline/services/router/interface.go +++ b/svc/frontline/services/router/interface.go @@ -5,7 +5,6 @@ import ( "github.com/unkeyed/unkey/pkg/cache" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) type RouteDecision struct { @@ -25,7 +24,6 @@ type Service interface { } type Config struct { - Logger logging.Logger Region string DB db.Database FrontlineRouteCache cache.Cache[string, db.FrontlineRoute] diff --git a/svc/frontline/services/router/service.go b/svc/frontline/services/router/service.go index ed002985f3..e2c90aaba6 100644 --- a/svc/frontline/services/router/service.go +++ b/svc/frontline/services/router/service.go @@ -8,7 +8,6 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // regionProximity maps regions to their closest regions in order of proximity. @@ -42,7 +41,6 @@ var regionProximity = map[string][]string{ } type service struct { - logger logging.Logger region string db db.Database frontlineRouteCache cache.Cache[string, db.FrontlineRoute] @@ -53,7 +51,6 @@ var _ Service = (*service)(nil) func New(cfg Config) (*service, error) { return &service{ - logger: cfg.Logger, region: cfg.Region, db: cfg.DB, frontlineRouteCache: cfg.FrontlineRouteCache, diff --git a/svc/krane/BUILD.bazel b/svc/krane/BUILD.bazel index 899aae26a5..dc77a50c05 100644 --- a/svc/krane/BUILD.bazel +++ b/svc/krane/BUILD.bazel @@ -13,8 +13,8 @@ go_library( "//gen/proto/krane/v1/kranev1connect", "//gen/proto/vault/v1/vaultv1connect", "//pkg/clock", + "//pkg/logger", "//pkg/otel", - "//pkg/otel/logging", "//pkg/prometheus", "//pkg/rpc/interceptor", "//pkg/runner", diff --git a/svc/krane/config.go b/svc/krane/config.go index 3d0467ee75..df5e3d2e59 100644 --- a/svc/krane/config.go +++ b/svc/krane/config.go @@ -1,6 +1,8 @@ package krane import ( + "time" + "github.com/unkeyed/unkey/pkg/clock" ) @@ -68,6 +70,14 @@ type Config struct { // OtelTraceSamplingRate controls the sampling rate for traces (0.0 to 1.0). // Only used when OtelEnabled is true. OtelTraceSamplingRate float64 + + // --- Logging sampler configuration --- + + // LogSampleRate is the baseline probability (0.0-1.0) of emitting log events. + LogSampleRate float64 + + // LogSlowThreshold defines what duration qualifies as "slow" for sampling. + LogSlowThreshold time.Duration } // Validate checks the configuration for required fields and logical consistency. diff --git a/svc/krane/internal/cilium/BUILD.bazel b/svc/krane/internal/cilium/BUILD.bazel index d5a69e5e4d..bdceb38929 100644 --- a/svc/krane/internal/cilium/BUILD.bazel +++ b/svc/krane/internal/cilium/BUILD.bazel @@ -18,7 +18,7 @@ go_library( "//gen/proto/ctrl/v1:ctrl", "//gen/proto/ctrl/v1/ctrlv1connect", "//pkg/assert", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/repeat", "//svc/krane/pkg/labels", "@com_connectrpc_connect//:connect", diff --git a/svc/krane/internal/cilium/apply.go b/svc/krane/internal/cilium/apply.go index 5d5179ca46..027ee3a49e 100644 --- a/svc/krane/internal/cilium/apply.go +++ b/svc/krane/internal/cilium/apply.go @@ -7,6 +7,7 @@ import ( ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" "github.com/unkeyed/unkey/pkg/assert" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/svc/krane/pkg/labels" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -21,7 +22,7 @@ import ( // ApplyCiliumNetworkPolicy validates required fields and returns an error if any are missing // or invalid: K8sNamespace, K8sName, CiliumNetworkPolicyId, and Policy must be non-empty. func (c *Controller) ApplyCiliumNetworkPolicy(ctx context.Context, req *ctrlv1.ApplyCiliumNetworkPolicy) error { - c.logger.Info("applying cilium network policy", + logger.Info("applying cilium network policy", "namespace", req.GetK8SNamespace(), "name", req.GetK8SName(), "policy_id", req.GetCiliumNetworkPolicyId(), diff --git a/svc/krane/internal/cilium/controller.go b/svc/krane/internal/cilium/controller.go index a276392561..e664b792af 100644 --- a/svc/krane/internal/cilium/controller.go +++ b/svc/krane/internal/cilium/controller.go @@ -4,7 +4,6 @@ import ( "context" "github.com/unkeyed/unkey/gen/proto/ctrl/v1/ctrlv1connect" - "github.com/unkeyed/unkey/pkg/otel/logging" "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes" ) @@ -21,7 +20,6 @@ import ( type Controller struct { clientSet kubernetes.Interface dynamicClient dynamic.Interface - logger logging.Logger cluster ctrlv1connect.ClusterServiceClient done chan struct{} region string @@ -41,9 +39,6 @@ type Config struct { // resources that don't have generated Go types. DynamicClient dynamic.Interface - // Logger is the structured logger for controller operations. - Logger logging.Logger - // Cluster is the control plane RPC client for WatchCiliumNetworkPolicies calls. Cluster ctrlv1connect.ClusterServiceClient @@ -60,7 +55,6 @@ func New(cfg Config) *Controller { return &Controller{ clientSet: cfg.ClientSet, dynamicClient: cfg.DynamicClient, - logger: cfg.Logger.With("controller", "cilium"), cluster: cfg.Cluster, done: make(chan struct{}), region: cfg.Region, diff --git a/svc/krane/internal/cilium/delete.go b/svc/krane/internal/cilium/delete.go index 21092e8789..363b630683 100644 --- a/svc/krane/internal/cilium/delete.go +++ b/svc/krane/internal/cilium/delete.go @@ -5,6 +5,7 @@ import ( "fmt" ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" + "github.com/unkeyed/unkey/pkg/logger" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -17,7 +18,7 @@ import ( // already achieved. The method is idempotent: calling it multiple times for the // same policy succeeds without error. func (c *Controller) DeleteCiliumNetworkPolicy(ctx context.Context, req *ctrlv1.DeleteCiliumNetworkPolicy) error { - c.logger.Info("deleting cilium network policy", + logger.Info("deleting cilium network policy", "namespace", req.GetK8SNamespace(), "name", req.GetK8SName(), ) diff --git a/svc/krane/internal/cilium/desired_state_apply.go b/svc/krane/internal/cilium/desired_state_apply.go index 0cd376e93b..41f6e77887 100644 --- a/svc/krane/internal/cilium/desired_state_apply.go +++ b/svc/krane/internal/cilium/desired_state_apply.go @@ -7,6 +7,7 @@ import ( "connectrpc.com/connect" ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" + "github.com/unkeyed/unkey/pkg/logger" ) // runDesiredStateApplyLoop connects to the control plane's WatchCiliumNetworkPolicies @@ -29,7 +30,7 @@ func (c *Controller) runDesiredStateApplyLoop(ctx context.Context) { err := c.streamDesiredStateOnce(ctx) if err != nil { - c.logger.Error("error streaming desired state from control plane", "error", err) + logger.Error("error streaming desired state from control plane", "error", err) } } } @@ -46,7 +47,7 @@ func (c *Controller) runDesiredStateApplyLoop(ctx context.Context) { // // The caller ([Controller.runDesiredStateApplyLoop]) handles reconnection on error. func (c *Controller) streamDesiredStateOnce(ctx context.Context) error { - c.logger.Info("connecting to control plane for desired state") + logger.Info("connecting to control plane for desired state") stream, err := c.cluster.WatchCiliumNetworkPolicies(ctx, connect.NewRequest(&ctrlv1.WatchCiliumNetworkPoliciesRequest{ Region: c.region, @@ -57,7 +58,7 @@ func (c *Controller) streamDesiredStateOnce(ctx context.Context) error { } for stream.Receive() { - c.logger.Info("received desired state from control plane") + logger.Info("received desired state from control plane") state := stream.Msg() switch op := state.GetState().(type) { @@ -77,7 +78,7 @@ func (c *Controller) streamDesiredStateOnce(ctx context.Context) error { } if err := stream.Close(); err != nil { - c.logger.Error("unable to close control plane stream", "error", err) + logger.Error("unable to close control plane stream", "error", err) return err } diff --git a/svc/krane/internal/cilium/doc.go b/svc/krane/internal/cilium/doc.go index d549263827..4ff9b5b6a3 100644 --- a/svc/krane/internal/cilium/doc.go +++ b/svc/krane/internal/cilium/doc.go @@ -22,7 +22,6 @@ // controller := cilium.New(cilium.Config{ // ClientSet: clientSet, // DynamicClient: dynamicClient, -// Logger: logger, // Cluster: clusterClient, // Region: "us-east-1", // }) diff --git a/svc/krane/internal/cilium/resync.go b/svc/krane/internal/cilium/resync.go index 97c595761f..c4e39f1a3b 100644 --- a/svc/krane/internal/cilium/resync.go +++ b/svc/krane/internal/cilium/resync.go @@ -6,6 +6,7 @@ import ( "connectrpc.com/connect" ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/repeat" "github.com/unkeyed/unkey/svc/krane/pkg/labels" ) @@ -25,20 +26,20 @@ import ( // policies. func (c *Controller) runResyncLoop(ctx context.Context) { repeat.Every(1*time.Minute, func() { - c.logger.Info("running periodic resync") + logger.Info("running periodic resync") cursor := "" for { policies, err := c.listCiliumNetworkPolicies(ctx, cursor) if err != nil { - c.logger.Error("unable to list cilium network policies", "error", err.Error()) + logger.Error("unable to list cilium network policies", "error", err.Error()) return } for _, policy := range policies.Items { policyID, ok := labels.GetCiliumNetworkPolicyID(policy.GetLabels()) if !ok { - c.logger.Error("unable to get cilium network policy id", "policy", policy.GetName()) + logger.Error("unable to get cilium network policy id", "policy", policy.GetName()) continue } @@ -51,23 +52,23 @@ func (c *Controller) runResyncLoop(ctx context.Context) { K8SNamespace: policy.GetNamespace(), K8SName: policy.GetName(), }); err != nil { - c.logger.Error("unable to delete cilium network policy", "error", err.Error(), "policy_id", policyID) + logger.Error("unable to delete cilium network policy", "error", err.Error(), "policy_id", policyID) continue } } - c.logger.Error("unable to get desired cilium network policy state", "error", err.Error(), "policy_id", policyID) + logger.Error("unable to get desired cilium network policy state", "error", err.Error(), "policy_id", policyID) continue } switch res.Msg.GetState().(type) { case *ctrlv1.CiliumNetworkPolicyState_Apply: if err := c.ApplyCiliumNetworkPolicy(ctx, res.Msg.GetApply()); err != nil { - c.logger.Error("unable to apply cilium network policy", "error", err.Error(), "policy_id", policyID) + logger.Error("unable to apply cilium network policy", "error", err.Error(), "policy_id", policyID) } case *ctrlv1.CiliumNetworkPolicyState_Delete: if err := c.DeleteCiliumNetworkPolicy(ctx, res.Msg.GetDelete()); err != nil { - c.logger.Error("unable to delete cilium network policy", "error", err.Error(), "policy_id", policyID) + logger.Error("unable to delete cilium network policy", "error", err.Error(), "policy_id", policyID) } } } diff --git a/svc/krane/internal/deployment/BUILD.bazel b/svc/krane/internal/deployment/BUILD.bazel index 4a4eb46d8d..c24c56a45e 100644 --- a/svc/krane/internal/deployment/BUILD.bazel +++ b/svc/krane/internal/deployment/BUILD.bazel @@ -22,7 +22,7 @@ go_library( "//gen/proto/ctrl/v1/ctrlv1connect", "//pkg/assert", "//pkg/circuitbreaker", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/ptr", "//pkg/repeat", "//svc/krane/pkg/labels", @@ -44,7 +44,6 @@ go_test( srcs = ["controller_test.go"], embed = [":deployment"], deps = [ - "//pkg/otel/logging", "//svc/krane/internal/testutil", "@com_github_stretchr_testify//require", "@io_k8s_api//core/v1:core", diff --git a/svc/krane/internal/deployment/actual_state_report.go b/svc/krane/internal/deployment/actual_state_report.go index 10f0b51850..713aee81b7 100644 --- a/svc/krane/internal/deployment/actual_state_report.go +++ b/svc/krane/internal/deployment/actual_state_report.go @@ -4,6 +4,7 @@ import ( "context" ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/svc/krane/pkg/labels" appsv1 "k8s.io/api/apps/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -37,28 +38,28 @@ func (c *Controller) runActualStateReportLoop(ctx context.Context) error { for event := range w.ResultChan() { switch event.Type { case watch.Error: - c.logger.Error("error watching deployment", "event", event.Object) + logger.Error("error watching deployment", "event", event.Object) case watch.Bookmark: case watch.Added, watch.Modified: replicaset, ok := event.Object.(*appsv1.ReplicaSet) if !ok { - c.logger.Error("unable to cast object to replicaset") + logger.Error("unable to cast object to replicaset") continue } status, err := c.buildDeploymentStatus(ctx, replicaset) if err != nil { - c.logger.Error("unable to build status", "error", err.Error()) + logger.Error("unable to build status", "error", err.Error()) continue } err = c.reportDeploymentStatus(ctx, status) if err != nil { - c.logger.Error("unable to report status", "error", err.Error()) + logger.Error("unable to report status", "error", err.Error()) continue } case watch.Deleted: replicaset, ok := event.Object.(*appsv1.ReplicaSet) if !ok { - c.logger.Error("unable to cast object to replicaset") + logger.Error("unable to cast object to replicaset") continue } err := c.reportDeploymentStatus(ctx, &ctrlv1.ReportDeploymentStatusRequest{ @@ -69,7 +70,7 @@ func (c *Controller) runActualStateReportLoop(ctx context.Context) error { }, }) if err != nil { - c.logger.Error("unable to report status", "error", err.Error()) + logger.Error("unable to report status", "error", err.Error()) continue } } diff --git a/svc/krane/internal/deployment/apply.go b/svc/krane/internal/deployment/apply.go index 5ca42cb0a4..5d84d7e642 100644 --- a/svc/krane/internal/deployment/apply.go +++ b/svc/krane/internal/deployment/apply.go @@ -9,6 +9,7 @@ import ( ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" "github.com/unkeyed/unkey/pkg/assert" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/svc/krane/pkg/labels" appsv1 "k8s.io/api/apps/v1" @@ -33,7 +34,7 @@ import ( // isolation (RuntimeClass "gvisor") since they execute untrusted user code, and are // scheduled on Karpenter-managed untrusted nodes with zone-spread constraints. func (c *Controller) ApplyDeployment(ctx context.Context, req *ctrlv1.ApplyDeployment) error { - c.logger.Info("applying deployment", + logger.Info("applying deployment", "namespace", req.GetK8SNamespace(), "name", req.GetK8SName(), "deployment_id", req.GetDeploymentId(), @@ -134,7 +135,7 @@ func (c *Controller) ApplyDeployment(ctx context.Context, req *ctrlv1.ApplyDeplo err = c.reportDeploymentStatus(ctx, status) if err != nil { - c.logger.Error("failed to report deployment status", "deployment_id", req.GetDeploymentId(), "error", err) + logger.Error("failed to report deployment status", "deployment_id", req.GetDeploymentId(), "error", err) return err } diff --git a/svc/krane/internal/deployment/controller.go b/svc/krane/internal/deployment/controller.go index 836a67e696..f779dcabc5 100644 --- a/svc/krane/internal/deployment/controller.go +++ b/svc/krane/internal/deployment/controller.go @@ -8,7 +8,6 @@ import ( ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" "github.com/unkeyed/unkey/gen/proto/ctrl/v1/ctrlv1connect" "github.com/unkeyed/unkey/pkg/circuitbreaker" - "github.com/unkeyed/unkey/pkg/otel/logging" "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes" ) @@ -26,7 +25,6 @@ import ( type Controller struct { clientSet kubernetes.Interface dynamicClient dynamic.Interface - logger logging.Logger cluster ctrlv1connect.ClusterServiceClient cb circuitbreaker.CircuitBreaker[any] done chan struct{} @@ -47,9 +45,6 @@ type Config struct { // resources that don't have generated Go types. DynamicClient dynamic.Interface - // Logger is the structured logger for controller operations. - Logger logging.Logger - // Cluster is the control plane RPC client for WatchDeployments and // ReportDeploymentStatus calls. Cluster ctrlv1connect.ClusterServiceClient @@ -67,7 +62,6 @@ func New(cfg Config) *Controller { return &Controller{ clientSet: cfg.ClientSet, dynamicClient: cfg.DynamicClient, - logger: cfg.Logger.With("controller", "deployments"), cluster: cfg.Cluster, cb: circuitbreaker.New[any]("deployment_state_update"), done: make(chan struct{}), diff --git a/svc/krane/internal/deployment/controller_test.go b/svc/krane/internal/deployment/controller_test.go index 631a2d5ab6..b1163968b0 100644 --- a/svc/krane/internal/deployment/controller_test.go +++ b/svc/krane/internal/deployment/controller_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/svc/krane/internal/testutil" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -21,13 +20,11 @@ func TestNew_CreatesControllerWithCorrectFields(t *testing.T) { } client := fake.NewSimpleClientset(namespace) dynamicClient := fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()) - logger := logging.NewNoop() mockCluster := &testutil.MockClusterClient{} cfg := Config{ ClientSet: client, DynamicClient: dynamicClient, - Logger: logger, Cluster: mockCluster, Region: "us-east-1", } @@ -47,7 +44,6 @@ func TestNew_CreatesOwnCircuitBreaker(t *testing.T) { cfg := Config{ ClientSet: client, DynamicClient: dynamicClient, - Logger: logging.NewNoop(), Cluster: &testutil.MockClusterClient{}, Region: "us-east-1", } @@ -63,7 +59,6 @@ func TestNew_InitializesVersionCursorToZero(t *testing.T) { cfg := Config{ ClientSet: client, DynamicClient: dynamicClient, - Logger: logging.NewNoop(), Cluster: &testutil.MockClusterClient{}, Region: "us-east-1", } @@ -79,7 +74,6 @@ func TestNew_CreatesDoneChannel(t *testing.T) { cfg := Config{ ClientSet: client, DynamicClient: dynamicClient, - Logger: logging.NewNoop(), Cluster: &testutil.MockClusterClient{}, Region: "us-east-1", } @@ -101,7 +95,6 @@ func TestStop_ClosesDoneChannel(t *testing.T) { cfg := Config{ ClientSet: client, DynamicClient: dynamicClient, - Logger: logging.NewNoop(), Cluster: &testutil.MockClusterClient{}, Region: "us-east-1", } diff --git a/svc/krane/internal/deployment/delete.go b/svc/krane/internal/deployment/delete.go index 801ddd6d3b..9eeffddeb0 100644 --- a/svc/krane/internal/deployment/delete.go +++ b/svc/krane/internal/deployment/delete.go @@ -4,6 +4,7 @@ import ( "context" ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" + "github.com/unkeyed/unkey/pkg/logger" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" @@ -18,7 +19,7 @@ import ( // The method is idempotent: calling it multiple times for the same deployment // succeeds without error. func (c *Controller) DeleteDeployment(ctx context.Context, req *ctrlv1.DeleteDeployment) error { - c.logger.Info("deleting deployment", + logger.Info("deleting deployment", "namespace", req.GetK8SNamespace(), "name", req.GetK8SName(), ) diff --git a/svc/krane/internal/deployment/desired_state_apply.go b/svc/krane/internal/deployment/desired_state_apply.go index db1f36372a..605ed1fed3 100644 --- a/svc/krane/internal/deployment/desired_state_apply.go +++ b/svc/krane/internal/deployment/desired_state_apply.go @@ -7,6 +7,7 @@ import ( "connectrpc.com/connect" ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" + "github.com/unkeyed/unkey/pkg/logger" ) // runDesiredStateApplyLoop connects to the control plane's WatchDeployments @@ -29,7 +30,7 @@ func (c *Controller) runDesiredStateApplyLoop(ctx context.Context) { err := c.streamDesiredStateOnce(ctx) if err != nil { - c.logger.Error("error streaming desired state from control plane", "error", err) + logger.Error("error streaming desired state from control plane", "error", err) } } } @@ -46,7 +47,7 @@ func (c *Controller) runDesiredStateApplyLoop(ctx context.Context) { // // The caller ([Controller.runDesiredStateApplyLoop]) handles reconnection on error. func (c *Controller) streamDesiredStateOnce(ctx context.Context) error { - c.logger.Info("connecting to control plane for desired state") + logger.Info("connecting to control plane for desired state") stream, err := c.cluster.WatchDeployments(ctx, connect.NewRequest(&ctrlv1.WatchDeploymentsRequest{ Region: c.region, @@ -57,7 +58,7 @@ func (c *Controller) streamDesiredStateOnce(ctx context.Context) error { } for stream.Receive() { - c.logger.Info("received desired state from control plane") + logger.Info("received desired state from control plane") state := stream.Msg() switch op := state.GetState().(type) { @@ -77,7 +78,7 @@ func (c *Controller) streamDesiredStateOnce(ctx context.Context) error { } if err := stream.Close(); err != nil { - c.logger.Error("unable to close control plane stream", "error", err) + logger.Error("unable to close control plane stream", "error", err) return err } diff --git a/svc/krane/internal/deployment/doc.go b/svc/krane/internal/deployment/doc.go index 2830059e5b..e1cdf9fd9c 100644 --- a/svc/krane/internal/deployment/doc.go +++ b/svc/krane/internal/deployment/doc.go @@ -40,7 +40,6 @@ // ctrl := deployment.New(deployment.Config{ // ClientSet: kubeClient, // DynamicClient: dynamicClient, -// Logger: logger, // Cluster: clusterClient, // Region: "us-east-1", // }) diff --git a/svc/krane/internal/deployment/resync.go b/svc/krane/internal/deployment/resync.go index 6393e5f18e..6329f625d0 100644 --- a/svc/krane/internal/deployment/resync.go +++ b/svc/krane/internal/deployment/resync.go @@ -6,6 +6,7 @@ import ( "connectrpc.com/connect" ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/repeat" "github.com/unkeyed/unkey/svc/krane/pkg/labels" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -27,7 +28,7 @@ import ( // ReplicaSets. func (c *Controller) runResyncLoop(ctx context.Context) { repeat.Every(1*time.Minute, func() { - c.logger.Info("running periodic resync") + logger.Info("running periodic resync") cursor := "" for { @@ -39,14 +40,14 @@ func (c *Controller) runResyncLoop(ctx context.Context) { Continue: cursor, }) if err != nil { - c.logger.Error("unable to list replicaSets", "error", err.Error()) + logger.Error("unable to list replicaSets", "error", err.Error()) return } for _, replicaSet := range replicaSets.Items { deploymentID, ok := labels.GetDeploymentID(replicaSet.Labels) if !ok { - c.logger.Error("unable to get deployment ID", "replicaSet", replicaSet.Name) + logger.Error("unable to get deployment ID", "replicaSet", replicaSet.Name) continue } @@ -54,18 +55,18 @@ func (c *Controller) runResyncLoop(ctx context.Context) { DeploymentId: deploymentID, })) if err != nil { - c.logger.Error("unable to get desired deployment state", "error", err.Error(), "deployment_id", deploymentID) + logger.Error("unable to get desired deployment state", "error", err.Error(), "deployment_id", deploymentID) continue } switch res.Msg.GetState().(type) { case *ctrlv1.DeploymentState_Apply: if err := c.ApplyDeployment(ctx, res.Msg.GetApply()); err != nil { - c.logger.Error("unable to apply deployment", "error", err.Error(), "deployment_id", deploymentID) + logger.Error("unable to apply deployment", "error", err.Error(), "deployment_id", deploymentID) } case *ctrlv1.DeploymentState_Delete: if err := c.DeleteDeployment(ctx, res.Msg.GetDelete()); err != nil { - c.logger.Error("unable to delete deployment", "error", err.Error(), "deployment_id", deploymentID) + logger.Error("unable to delete deployment", "error", err.Error(), "deployment_id", deploymentID) } } } diff --git a/svc/krane/internal/sentinel/BUILD.bazel b/svc/krane/internal/sentinel/BUILD.bazel index 17dd596349..c47f4de2ff 100644 --- a/svc/krane/internal/sentinel/BUILD.bazel +++ b/svc/krane/internal/sentinel/BUILD.bazel @@ -19,7 +19,7 @@ go_library( "//gen/proto/ctrl/v1/ctrlv1connect", "//pkg/assert", "//pkg/circuitbreaker", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/ptr", "//pkg/repeat", "//svc/krane/pkg/labels", @@ -42,7 +42,6 @@ go_test( srcs = ["controller_test.go"], embed = [":sentinel"], deps = [ - "//pkg/otel/logging", "//svc/krane/internal/testutil", "@com_github_stretchr_testify//require", "@io_k8s_api//core/v1:core", diff --git a/svc/krane/internal/sentinel/actual_state_report.go b/svc/krane/internal/sentinel/actual_state_report.go index 347de8511a..d6ce392f56 100644 --- a/svc/krane/internal/sentinel/actual_state_report.go +++ b/svc/krane/internal/sentinel/actual_state_report.go @@ -4,6 +4,7 @@ import ( "context" ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/svc/krane/pkg/labels" appsv1 "k8s.io/api/apps/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -31,15 +32,15 @@ func (c *Controller) runActualStateReportLoop(ctx context.Context) error { for event := range w.ResultChan() { switch event.Type { case watch.Error: - c.logger.Error("error watching sentinel", "event", event.Object) + logger.Error("error watching sentinel", "event", event.Object) case watch.Bookmark: case watch.Added, watch.Modified: sentinel, ok := event.Object.(*appsv1.Deployment) if !ok { - c.logger.Error("unable to cast object to deployment") + logger.Error("unable to cast object to deployment") continue } - c.logger.Info("sentinel added/modified", "name", sentinel.Name) + logger.Info("sentinel added/modified", "name", sentinel.Name) desiredReplicas := int32(0) if sentinel.Spec.Replicas != nil { @@ -61,22 +62,22 @@ func (c *Controller) runActualStateReportLoop(ctx context.Context) error { Health: health, }) if err != nil { - c.logger.Error("error reporting sentinel status", "error", err.Error()) + logger.Error("error reporting sentinel status", "error", err.Error()) } case watch.Deleted: sentinel, ok := event.Object.(*appsv1.Deployment) if !ok { - c.logger.Error("unable to cast object to deployment") + logger.Error("unable to cast object to deployment") continue } - c.logger.Info("sentinel deleted", "name", sentinel.Name) + logger.Info("sentinel deleted", "name", sentinel.Name) err := c.reportSentinelStatus(ctx, &ctrlv1.ReportSentinelStatusRequest{ K8SName: sentinel.Name, AvailableReplicas: 0, Health: ctrlv1.Health_HEALTH_UNHEALTHY, }) if err != nil { - c.logger.Error("error reporting sentinel status", "error", err.Error()) + logger.Error("error reporting sentinel status", "error", err.Error()) } } } diff --git a/svc/krane/internal/sentinel/apply.go b/svc/krane/internal/sentinel/apply.go index 58185dfd11..ff63ca700d 100644 --- a/svc/krane/internal/sentinel/apply.go +++ b/svc/krane/internal/sentinel/apply.go @@ -8,6 +8,7 @@ import ( ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" "github.com/unkeyed/unkey/pkg/assert" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/ptr" "github.com/unkeyed/unkey/svc/krane/pkg/labels" appsv1 "k8s.io/api/apps/v1" @@ -29,7 +30,7 @@ import ( // ApplySentinel reports the available replica count back to the control plane after // applying, so the platform knows when the sentinel is ready to receive traffic. func (c *Controller) ApplySentinel(ctx context.Context, req *ctrlv1.ApplySentinel) error { - c.logger.Info("applying sentinel", + logger.Info("applying sentinel", "namespace", NamespaceSentinel, "name", req.GetK8SName(), "sentinel_id", req.GetSentinelId(), @@ -84,7 +85,7 @@ func (c *Controller) ApplySentinel(ctx context.Context, req *ctrlv1.ApplySentine Health: health, }) if err != nil { - c.logger.Error("failed to reconcile sentinel", "sentinel_id", req.GetSentinelId(), "error", err) + logger.Error("failed to reconcile sentinel", "sentinel_id", req.GetSentinelId(), "error", err) return err } diff --git a/svc/krane/internal/sentinel/controller.go b/svc/krane/internal/sentinel/controller.go index e7f5a6a77d..12dd2eb0f8 100644 --- a/svc/krane/internal/sentinel/controller.go +++ b/svc/krane/internal/sentinel/controller.go @@ -9,7 +9,6 @@ import ( ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" "github.com/unkeyed/unkey/gen/proto/ctrl/v1/ctrlv1connect" "github.com/unkeyed/unkey/pkg/circuitbreaker" - "github.com/unkeyed/unkey/pkg/otel/logging" "k8s.io/client-go/kubernetes" ) @@ -21,7 +20,6 @@ import ( // the DeploymentController with its own version cursor and circuit breaker. type Controller struct { clientSet kubernetes.Interface - logger logging.Logger cluster ctrlv1connect.ClusterServiceClient cb circuitbreaker.CircuitBreaker[any] done chan struct{} @@ -33,7 +31,6 @@ type Controller struct { // Config holds the configuration required to create a new [Controller]. type Config struct { ClientSet kubernetes.Interface - Logger logging.Logger Cluster ctrlv1connect.ClusterServiceClient Region string } @@ -42,7 +39,6 @@ type Config struct { func New(cfg Config) *Controller { return &Controller{ clientSet: cfg.ClientSet, - logger: cfg.Logger.With("controller", "sentinels"), cluster: cfg.Cluster, cb: circuitbreaker.New[any]("sentinel_state_update"), done: make(chan struct{}), diff --git a/svc/krane/internal/sentinel/controller_test.go b/svc/krane/internal/sentinel/controller_test.go index a1011fa57b..41a9ce7f31 100644 --- a/svc/krane/internal/sentinel/controller_test.go +++ b/svc/krane/internal/sentinel/controller_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/svc/krane/internal/testutil" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -18,12 +17,10 @@ func TestNew_CreatesControllerWithCorrectFields(t *testing.T) { }, } client := fake.NewSimpleClientset(namespace) - logger := logging.NewNoop() mockCluster := &testutil.MockClusterClient{} cfg := Config{ ClientSet: client, - Logger: logger, Cluster: mockCluster, Region: "us-east-1", } @@ -40,7 +37,6 @@ func TestNew_CreatesOwnCircuitBreaker(t *testing.T) { client := fake.NewSimpleClientset() cfg := Config{ ClientSet: client, - Logger: logging.NewNoop(), Cluster: &testutil.MockClusterClient{}, Region: "us-east-1", } @@ -54,7 +50,6 @@ func TestNew_InitializesVersionCursorToZero(t *testing.T) { client := fake.NewSimpleClientset() cfg := Config{ ClientSet: client, - Logger: logging.NewNoop(), Cluster: &testutil.MockClusterClient{}, Region: "us-east-1", } @@ -68,7 +63,6 @@ func TestNew_CreatesDoneChannel(t *testing.T) { client := fake.NewSimpleClientset() cfg := Config{ ClientSet: client, - Logger: logging.NewNoop(), Cluster: &testutil.MockClusterClient{}, Region: "us-east-1", } @@ -88,7 +82,6 @@ func TestStop_ClosesDoneChannel(t *testing.T) { client := fake.NewSimpleClientset() cfg := Config{ ClientSet: client, - Logger: logging.NewNoop(), Cluster: &testutil.MockClusterClient{}, Region: "us-east-1", } diff --git a/svc/krane/internal/sentinel/delete.go b/svc/krane/internal/sentinel/delete.go index 415bc80cee..07b5767767 100644 --- a/svc/krane/internal/sentinel/delete.go +++ b/svc/krane/internal/sentinel/delete.go @@ -4,6 +4,7 @@ import ( "context" ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" + "github.com/unkeyed/unkey/pkg/logger" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" @@ -15,7 +16,7 @@ import ( // cascading, ensuring cleanup completes even if ownership wasn't set correctly. // Not-found errors are ignored since the desired end state is already achieved. func (c *Controller) DeleteSentinel(ctx context.Context, req *ctrlv1.DeleteSentinel) error { - c.logger.Info("deleting sentinel", + logger.Info("deleting sentinel", "namespace", NamespaceSentinel, "name", req.GetK8SName(), ) diff --git a/svc/krane/internal/sentinel/desired_state_apply.go b/svc/krane/internal/sentinel/desired_state_apply.go index 4ab9f038b9..8f39d1c66e 100644 --- a/svc/krane/internal/sentinel/desired_state_apply.go +++ b/svc/krane/internal/sentinel/desired_state_apply.go @@ -7,6 +7,7 @@ import ( "connectrpc.com/connect" ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" + "github.com/unkeyed/unkey/pkg/logger" ) // runDesiredStateApplyLoop connects to the control plane's SyncSentinels stream @@ -25,7 +26,7 @@ func (c *Controller) runDesiredStateApplyLoop(ctx context.Context) { err := c.streamDesiredStateOnce(ctx) if err != nil { - c.logger.Error("error streaming desired state from control plane", "error", err) + logger.Error("error streaming desired state from control plane", "error", err) } } } @@ -34,7 +35,7 @@ func (c *Controller) runDesiredStateApplyLoop(ctx context.Context) { // WatchSentinels stream, processes all received states until the stream // closes or errors, then returns. The caller handles reconnection. func (c *Controller) streamDesiredStateOnce(ctx context.Context) error { - c.logger.Info("connecting to control plane for desired state") + logger.Info("connecting to control plane for desired state") stream, err := c.cluster.WatchSentinels(ctx, connect.NewRequest(&ctrlv1.WatchSentinelsRequest{ Region: c.region, @@ -45,7 +46,7 @@ func (c *Controller) streamDesiredStateOnce(ctx context.Context) error { } for stream.Receive() { - c.logger.Info("received desired state from control plane") + logger.Info("received desired state from control plane") state := stream.Msg() switch op := state.GetState().(type) { @@ -64,7 +65,7 @@ func (c *Controller) streamDesiredStateOnce(ctx context.Context) error { } if err := stream.Close(); err != nil { - c.logger.Error("unable to close control plane stream", "error", err) + logger.Error("unable to close control plane stream", "error", err) return err } diff --git a/svc/krane/internal/sentinel/doc.go b/svc/krane/internal/sentinel/doc.go index ac4cae0d0c..224f03c0c0 100644 --- a/svc/krane/internal/sentinel/doc.go +++ b/svc/krane/internal/sentinel/doc.go @@ -39,7 +39,6 @@ // // ctrl := sentinel.New(sentinel.Config{ // ClientSet: kubeClient, -// Logger: logger.With("controller", "sentinels"), // Cluster: clusterClient, // Region: "us-east-1", // }) diff --git a/svc/krane/internal/sentinel/resync.go b/svc/krane/internal/sentinel/resync.go index 3968d5e73b..a6573b0daa 100644 --- a/svc/krane/internal/sentinel/resync.go +++ b/svc/krane/internal/sentinel/resync.go @@ -6,6 +6,7 @@ import ( "connectrpc.com/connect" ctrlv1 "github.com/unkeyed/unkey/gen/proto/ctrl/v1" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/repeat" "github.com/unkeyed/unkey/svc/krane/pkg/labels" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -22,7 +23,7 @@ import ( // for each existing sentinel and applying any needed changes. func (c *Controller) runResyncLoop(ctx context.Context) { repeat.Every(1*time.Minute, func() { - c.logger.Info("running periodic resync") + logger.Info("running periodic resync") cursor := "" for { @@ -34,14 +35,14 @@ func (c *Controller) runResyncLoop(ctx context.Context) { Continue: cursor, }) if err != nil { - c.logger.Error("unable to list deployments", "error", err.Error()) + logger.Error("unable to list deployments", "error", err.Error()) return } for _, deployment := range deployments.Items { sentinelID, ok := labels.GetSentinelID(deployment.Labels) if !ok { - c.logger.Error("unable to get sentinel ID", "deployment", deployment.Name) + logger.Error("unable to get sentinel ID", "deployment", deployment.Name) continue } @@ -49,18 +50,18 @@ func (c *Controller) runResyncLoop(ctx context.Context) { SentinelId: sentinelID, })) if err != nil { - c.logger.Error("unable to get desired sentinel state", "error", err.Error(), "sentinel_id", sentinelID) + logger.Error("unable to get desired sentinel state", "error", err.Error(), "sentinel_id", sentinelID) continue } switch res.Msg.GetState().(type) { case *ctrlv1.SentinelState_Apply: if err := c.ApplySentinel(ctx, res.Msg.GetApply()); err != nil { - c.logger.Error("unable to apply sentinel", "error", err.Error(), "sentinel_id", sentinelID) + logger.Error("unable to apply sentinel", "error", err.Error(), "sentinel_id", sentinelID) } case *ctrlv1.SentinelState_Delete: if err := c.DeleteSentinel(ctx, res.Msg.GetDelete()); err != nil { - c.logger.Error("unable to delete sentinel", "error", err.Error(), "sentinel_id", sentinelID) + logger.Error("unable to delete sentinel", "error", err.Error(), "sentinel_id", sentinelID) } } } diff --git a/svc/krane/run.go b/svc/krane/run.go index c6690e59c3..2cda5c19c0 100644 --- a/svc/krane/run.go +++ b/svc/krane/run.go @@ -12,8 +12,8 @@ import ( "connectrpc.com/connect" "github.com/unkeyed/unkey/gen/proto/krane/v1/kranev1connect" "github.com/unkeyed/unkey/gen/proto/vault/v1/vaultv1connect" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/prometheus" "github.com/unkeyed/unkey/pkg/rpc/interceptor" "github.com/unkeyed/unkey/pkg/runner" @@ -56,6 +56,11 @@ func Run(ctx context.Context, cfg Config) error { return fmt.Errorf("bad config: %w", err) } + logger.SetSampler(logger.TailSampler{ + SlowThreshold: cfg.LogSlowThreshold, + SampleRate: cfg.LogSampleRate, + }) + var shutdownGrafana func(context.Context) error if cfg.OtelEnabled { shutdownGrafana, err = otel.InitGrafana(ctx, otel.Config{ @@ -70,18 +75,18 @@ func Run(ctx context.Context, cfg Config) error { } } - logger := logging.New() - if cfg.InstanceID != "" { - logger = logger.With(slog.String("instanceID", cfg.InstanceID)) - } - if cfg.Region != "" { - logger = logger.With(slog.String("region", cfg.Region)) - } - if pkgversion.Version != "" { - logger = logger.With(slog.String("version", pkgversion.Version)) - } + // Add base attributes to global logger + logger.AddBaseAttrs(slog.GroupAttrs("instance", + slog.String("id", cfg.InstanceID), + slog.String("region", cfg.Region), + slog.String("version", pkgversion.Version), + )) + + r := runner.New() + defer r.Recover() + + r.DeferCtx(shutdownGrafana) - r := runner.New(logger) defer r.Recover() r.DeferCtx(shutdownGrafana) @@ -111,7 +116,6 @@ func Run(ctx context.Context, cfg Config) error { ciliumCtrl := cilium.New(cilium.Config{ ClientSet: clientset, DynamicClient: dynamicClient, - Logger: logger, Cluster: cluster, Region: cfg.Region, }) @@ -124,7 +128,6 @@ func Run(ctx context.Context, cfg Config) error { deploymentCtrl := deployment.New(deployment.Config{ ClientSet: clientset, DynamicClient: dynamicClient, - Logger: logger, Cluster: cluster, Region: cfg.Region, }) @@ -136,7 +139,6 @@ func Run(ctx context.Context, cfg Config) error { // Start the sentinel controller (independent control loop) sentinelCtrl := sentinel.New(sentinel.Config{ ClientSet: clientset, - Logger: logger, Cluster: cluster, Region: cfg.Region, }) @@ -169,7 +171,6 @@ func Run(ctx context.Context, cfg Config) error { // Register secrets service if vault is configured if vaultClient != nil { secretsSvc := secrets.New(secrets.Config{ - Logger: logger, Vault: vaultClient, TokenValidator: tokenValidator, }) @@ -204,9 +205,7 @@ func Run(ctx context.Context, cfg Config) error { if cfg.PrometheusPort > 0 { - prom, err := prometheus.New(prometheus.Config{ - Logger: logger, - }) + prom, err := prometheus.New() if err != nil { return fmt.Errorf("failed to create prometheus server: %w", err) } diff --git a/svc/krane/secrets/BUILD.bazel b/svc/krane/secrets/BUILD.bazel index 4699e16690..0d628a9269 100644 --- a/svc/krane/secrets/BUILD.bazel +++ b/svc/krane/secrets/BUILD.bazel @@ -14,7 +14,7 @@ go_library( "//gen/proto/krane/v1/kranev1connect", "//gen/proto/vault/v1:vault", "//gen/proto/vault/v1/vaultv1connect", - "//pkg/otel/logging", + "//pkg/logger", "//svc/krane/secrets/token", "@com_connectrpc_connect//:connect", "@org_golang_google_protobuf//encoding/protojson", diff --git a/svc/krane/secrets/doc.go b/svc/krane/secrets/doc.go index 1bda968bdd..4200d24d9e 100644 --- a/svc/krane/secrets/doc.go +++ b/svc/krane/secrets/doc.go @@ -37,7 +37,6 @@ // Basic service setup with vault and token validation: // // cfg := secrets.Config{ -// Logger: logger, // Vault: vaultService, // TokenValidator: tokenValidator, // } diff --git a/svc/krane/secrets/service.go b/svc/krane/secrets/service.go index 680648a151..64295722b0 100644 --- a/svc/krane/secrets/service.go +++ b/svc/krane/secrets/service.go @@ -10,7 +10,7 @@ import ( "github.com/unkeyed/unkey/gen/proto/krane/v1/kranev1connect" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" "github.com/unkeyed/unkey/gen/proto/vault/v1/vaultv1connect" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "google.golang.org/protobuf/encoding/protojson" "github.com/unkeyed/unkey/svc/krane/secrets/token" @@ -21,10 +21,6 @@ import ( // This configuration provides the vault client for decryption operations // and token validator for request authentication. type Config struct { - // Logger for secrets operations and security events. - // Should include correlation information for audit trails. - Logger logging.Logger - // Vault provides secure decryption services for encrypted secrets via the vault API. Vault vaultv1connect.VaultServiceClient @@ -35,7 +31,6 @@ type Config struct { type Service struct { kranev1connect.UnimplementedSecretsServiceHandler - logger logging.Logger vault vaultv1connect.VaultServiceClient tokenValidator token.Validator } @@ -50,7 +45,6 @@ type Service struct { func New(cfg Config) *Service { return &Service{ UnimplementedSecretsServiceHandler: kranev1connect.UnimplementedSecretsServiceHandler{}, - logger: cfg.Logger, vault: cfg.Vault, tokenValidator: cfg.TokenValidator, } @@ -82,14 +76,14 @@ func (s *Service) DecryptSecretsBlob( requestToken := req.Msg.GetToken() Encrypted := req.Msg.GetEncryptedBlob() - s.logger.Info("DecryptSecretsBlob request", + logger.Info("DecryptSecretsBlob request", "deployment_id", deploymentID, "environment_id", environmentID, ) _, err := s.tokenValidator.Validate(ctx, requestToken, deploymentID, environmentID) if err != nil { - s.logger.Warn("token validation failed", + logger.Warn("token validation failed", "deployment_id", deploymentID, "environment_id", environmentID, "error", err, @@ -107,7 +101,7 @@ func (s *Service) DecryptSecretsBlob( // Individual values are vault-encrypted, the blob itself is not. var secretsConfig ctrlv1.SecretsConfig if err := protojson.Unmarshal(Encrypted, &secretsConfig); err != nil { - s.logger.Error("failed to unmarshal secrets config", + logger.Error("failed to unmarshal secrets config", "deployment_id", deploymentID, "environment_id", environmentID, "error", err, @@ -123,7 +117,7 @@ func (s *Service) DecryptSecretsBlob( Encrypted: encryptedValue, })) if decryptErr != nil { - s.logger.Error("failed to decrypt env var", + logger.Error("failed to decrypt env var", "deployment_id", deploymentID, "environment_id", environmentID, "key", key, @@ -134,7 +128,7 @@ func (s *Service) DecryptSecretsBlob( envVars[key] = decrypted.Msg.GetPlaintext() } - s.logger.Info("decrypted secrets blob", + logger.Info("decrypted secrets blob", "deployment_id", deploymentID, "num_secrets", len(envVars), ) diff --git a/svc/preflight/BUILD.bazel b/svc/preflight/BUILD.bazel index 365312aa2f..0d050223e8 100644 --- a/svc/preflight/BUILD.bazel +++ b/svc/preflight/BUILD.bazel @@ -10,7 +10,7 @@ go_library( visibility = ["//visibility:public"], deps = [ "//pkg/assert", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/runner", "//pkg/tls", "//pkg/zen", diff --git a/svc/preflight/config.go b/svc/preflight/config.go index 3cde4edfc2..0419ff36c4 100644 --- a/svc/preflight/config.go +++ b/svc/preflight/config.go @@ -1,6 +1,10 @@ package preflight -import "github.com/unkeyed/unkey/pkg/assert" +import ( + "time" + + "github.com/unkeyed/unkey/pkg/assert" +) var validImagePullPolicies = map[string]bool{ "Always": true, @@ -18,6 +22,14 @@ type Config struct { DepotToken string InsecureRegistries []string RegistryAliases []string + + // --- Logging sampler configuration --- + + // LogSampleRate is the baseline probability (0.0-1.0) of emitting log events. + LogSampleRate float64 + + // LogSlowThreshold defines what duration qualifies as "slow" for sampling. + LogSlowThreshold time.Duration } func (c *Config) Validate() error { diff --git a/svc/preflight/internal/services/cleanup/BUILD.bazel b/svc/preflight/internal/services/cleanup/BUILD.bazel index d16d3256da..9a58b21f81 100644 --- a/svc/preflight/internal/services/cleanup/BUILD.bazel +++ b/svc/preflight/internal/services/cleanup/BUILD.bazel @@ -6,7 +6,7 @@ go_library( importpath = "github.com/unkeyed/unkey/svc/preflight/internal/services/cleanup", visibility = ["//svc/preflight:__subpackages__"], deps = [ - "//pkg/otel/logging", + "//pkg/logger", "@io_k8s_api//core/v1:core", "@io_k8s_apimachinery//pkg/apis/meta/v1:meta", "@io_k8s_client_go//kubernetes", diff --git a/svc/preflight/internal/services/cleanup/cleanup.go b/svc/preflight/internal/services/cleanup/cleanup.go index ff9676ad77..6b97d12478 100644 --- a/svc/preflight/internal/services/cleanup/cleanup.go +++ b/svc/preflight/internal/services/cleanup/cleanup.go @@ -8,7 +8,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) const ( @@ -18,18 +18,15 @@ const ( ) type Config struct { - Logger logging.Logger Clientset kubernetes.Interface } type Service struct { - logger logging.Logger clientset kubernetes.Interface } func New(cfg *Config) *Service { return &Service{ - logger: cfg.Logger, clientset: cfg.Clientset, } } @@ -44,7 +41,7 @@ func (s *Service) Start(ctx context.Context) { select { case <-ctx.Done(): - s.logger.Info("stopping secret cleanup loop") + logger.Info("stopping secret cleanup loop") return case <-ticker.C: } @@ -53,14 +50,14 @@ func (s *Service) Start(ctx context.Context) { // cleanupExpiredSecrets deletes all preflight-managed secrets that have expired. func (s *Service) cleanupExpiredSecrets(ctx context.Context) { - s.logger.Debug("running expired secret cleanup") + logger.Debug("running expired secret cleanup") // List all secrets managed by preflight across all namespaces secrets, err := s.clientset.CoreV1().Secrets("").List(ctx, metav1.ListOptions{ LabelSelector: labelSelector, }) if err != nil { - s.logger.Error("failed to list secrets for cleanup", "error", err) + logger.Error("failed to list secrets for cleanup", "error", err) return } @@ -73,7 +70,7 @@ func (s *Service) cleanupExpiredSecrets(ctx context.Context) { // Secret is expired or has no valid expiry annotation err := s.clientset.CoreV1().Secrets(secret.Namespace).Delete(ctx, secret.Name, metav1.DeleteOptions{}) if err != nil { - s.logger.Warn("failed to delete expired secret", + logger.Warn("failed to delete expired secret", "namespace", secret.Namespace, "secret", secret.Name, "error", err, @@ -82,10 +79,10 @@ func (s *Service) cleanupExpiredSecrets(ctx context.Context) { } deleted++ - s.logger.Info("deleted expired pull secret", "namespace", secret.Namespace, "secret", secret.Name) + logger.Info("deleted expired pull secret", "namespace", secret.Namespace, "secret", secret.Name) } - s.logger.Info("cleanup complete", "deleted", deleted) + logger.Info("cleanup complete", "deleted", deleted) } // isSecretValid checks if the secret's token hasn't expired. @@ -101,7 +98,7 @@ func (s *Service) isSecretValid(secret *corev1.Secret) bool { expiresAt, err := time.Parse(time.RFC3339, expiresAtStr) if err != nil { - s.logger.Warn("invalid expires-at annotation", "value", expiresAtStr, "error", err) + logger.Warn("invalid expires-at annotation", "value", expiresAtStr, "error", err) return false } diff --git a/svc/preflight/internal/services/mutator/BUILD.bazel b/svc/preflight/internal/services/mutator/BUILD.bazel index 92fa8c8010..fe074f82ef 100644 --- a/svc/preflight/internal/services/mutator/BUILD.bazel +++ b/svc/preflight/internal/services/mutator/BUILD.bazel @@ -11,7 +11,7 @@ go_library( visibility = ["//svc/preflight:__subpackages__"], deps = [ "//pkg/assert", - "//pkg/otel/logging", + "//pkg/logger", "//svc/preflight/internal/services/registry", "//svc/preflight/internal/services/registry/credentials", "@io_k8s_api//core/v1:core", diff --git a/svc/preflight/internal/services/mutator/config.go b/svc/preflight/internal/services/mutator/config.go index 1bed5642aa..95df57aab6 100644 --- a/svc/preflight/internal/services/mutator/config.go +++ b/svc/preflight/internal/services/mutator/config.go @@ -4,7 +4,6 @@ import ( "k8s.io/client-go/kubernetes" "github.com/unkeyed/unkey/pkg/assert" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/svc/preflight/internal/services/registry" "github.com/unkeyed/unkey/svc/preflight/internal/services/registry/credentials" ) @@ -24,7 +23,6 @@ const ( ) type Config struct { - Logger logging.Logger Registry *registry.Registry Clientset kubernetes.Interface Credentials *credentials.Manager diff --git a/svc/preflight/internal/services/mutator/mutator.go b/svc/preflight/internal/services/mutator/mutator.go index d4667235b7..1882d36a9d 100644 --- a/svc/preflight/internal/services/mutator/mutator.go +++ b/svc/preflight/internal/services/mutator/mutator.go @@ -13,7 +13,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/svc/preflight/internal/services/registry" "github.com/unkeyed/unkey/svc/preflight/internal/services/registry/credentials" ) @@ -26,7 +26,6 @@ const ( ) type Mutator struct { - logger logging.Logger registry *registry.Registry clientset kubernetes.Interface credentials *credentials.Manager @@ -37,7 +36,6 @@ type Mutator struct { func New(cfg Config) *Mutator { return &Mutator{ - logger: cfg.Logger, registry: cfg.Registry, clientset: cfg.Clientset, credentials: cfg.Credentials, @@ -164,7 +162,7 @@ func (m *Mutator) ensurePullSecrets(ctx context.Context, pod *corev1.Pod, namesp for _, image := range images { secretName, err := m.ensurePullSecretForImage(ctx, namespace, image, buildID) if err != nil { - m.logger.Error("failed to ensure pull secret for image", + logger.Error("failed to ensure pull secret for image", "image", image, "error", err, ) @@ -224,19 +222,19 @@ func (m *Mutator) ensurePullSecretForImage(ctx context.Context, namespace, image if err == nil { // Secret exists - check if it's still valid if m.isSecretValid(existing) { - m.logger.Debug("reusing existing pull secret", + logger.Debug("reusing existing pull secret", "secret", secretName, "image", image, ) return secretName, nil } // Secret expired - delete and recreate - m.logger.Info("pull secret expired, refreshing", + logger.Info("pull secret expired, refreshing", "secret", secretName, "image", image, ) if delErr := m.clientset.CoreV1().Secrets(namespace).Delete(ctx, secretName, metav1.DeleteOptions{}); delErr != nil { - m.logger.Warn("failed to delete expired secret", "error", delErr) + logger.Warn("failed to delete expired secret", "error", delErr) } } else if !apierrors.IsNotFound(err) { return "", fmt.Errorf("failed to check for existing secret: %w", err) @@ -286,7 +284,7 @@ func (m *Mutator) ensurePullSecretForImage(ctx context.Context, namespace, image return "", fmt.Errorf("failed to create secret: %w", err) } - m.logger.Info("created pull secret", + logger.Info("created pull secret", "namespace", namespace, "secret", secretName, "image", image, @@ -309,7 +307,7 @@ func (m *Mutator) isSecretValid(secret *corev1.Secret) bool { expiresAt, err := time.Parse(time.RFC3339, expiresAtStr) if err != nil { - m.logger.Warn("invalid expires-at annotation", "value", expiresAtStr, "error", err) + logger.Warn("invalid expires-at annotation", "value", expiresAtStr, "error", err) return false } diff --git a/svc/preflight/internal/services/mutator/patch.go b/svc/preflight/internal/services/mutator/patch.go index 5cae7f50ad..c395562058 100644 --- a/svc/preflight/internal/services/mutator/patch.go +++ b/svc/preflight/internal/services/mutator/patch.go @@ -5,6 +5,8 @@ import ( "fmt" corev1 "k8s.io/api/core/v1" + + "github.com/unkeyed/unkey/pkg/logger" ) func (m *Mutator) buildInitContainer() corev1.Container { @@ -87,7 +89,7 @@ func (m *Mutator) buildContainerPatches( // fetch the image's ENTRYPOINT/CMD from the registry so we know what to exec into. var args []string if len(container.Command) == 0 { - m.logger.Info("container has no command, fetching from registry", + logger.Info("container has no command, fetching from registry", "container", container.Name, "image", container.Image, ) diff --git a/svc/preflight/internal/services/registry/BUILD.bazel b/svc/preflight/internal/services/registry/BUILD.bazel index d315019fc1..97b60f018a 100644 --- a/svc/preflight/internal/services/registry/BUILD.bazel +++ b/svc/preflight/internal/services/registry/BUILD.bazel @@ -6,7 +6,7 @@ go_library( importpath = "github.com/unkeyed/unkey/svc/preflight/internal/services/registry", visibility = ["//svc/preflight:__subpackages__"], deps = [ - "//pkg/otel/logging", + "//pkg/logger", "//svc/preflight/internal/services/registry/credentials", "@com_github_google_go_containerregistry//pkg/authn", "@com_github_google_go_containerregistry//pkg/name", diff --git a/svc/preflight/internal/services/registry/credentials/BUILD.bazel b/svc/preflight/internal/services/registry/credentials/BUILD.bazel index 8794c1b58c..31a1b8a2ce 100644 --- a/svc/preflight/internal/services/registry/credentials/BUILD.bazel +++ b/svc/preflight/internal/services/registry/credentials/BUILD.bazel @@ -9,7 +9,6 @@ go_library( importpath = "github.com/unkeyed/unkey/svc/preflight/internal/services/registry/credentials", visibility = ["//svc/preflight:__subpackages__"], deps = [ - "//pkg/otel/logging", "@com_connectrpc_connect//:connect", "@com_github_depot_depot_go//proto/depot/cli/v1:cli", "@com_github_depot_depot_go//proto/depot/cli/v1/cliv1connect", diff --git a/svc/preflight/internal/services/registry/credentials/depot.go b/svc/preflight/internal/services/registry/credentials/depot.go index 2bc0f93762..09787eab36 100644 --- a/svc/preflight/internal/services/registry/credentials/depot.go +++ b/svc/preflight/internal/services/registry/credentials/depot.go @@ -9,8 +9,6 @@ import ( "connectrpc.com/connect" cliv1 "github.com/depot/depot-go/proto/depot/cli/v1" "github.com/depot/depot-go/proto/depot/cli/v1/cliv1connect" - - "github.com/unkeyed/unkey/pkg/otel/logging" ) const ( @@ -20,19 +18,16 @@ const ( // Depot fetches on-demand pull tokens from the Depot API for each image. type Depot struct { - logger logging.Logger buildClient cliv1connect.BuildServiceClient } type DepotConfig struct { - Logger logging.Logger - Token string + Token string } // NewDepot creates a Depot registry that fetches on-demand pull tokens. func NewDepot(cfg *DepotConfig) *Depot { return &Depot{ - logger: cfg.Logger, buildClient: cliv1connect.NewBuildServiceClient( http.DefaultClient, depotAPIURL, diff --git a/svc/preflight/internal/services/registry/registry.go b/svc/preflight/internal/services/registry/registry.go index 1bc7baa2fe..8b2071b4f4 100644 --- a/svc/preflight/internal/services/registry/registry.go +++ b/svc/preflight/internal/services/registry/registry.go @@ -14,7 +14,7 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/svc/preflight/internal/services/registry/credentials" ) @@ -26,7 +26,6 @@ type ImageConfig struct { } type Config struct { - Logger logging.Logger Clientset kubernetes.Interface Credentials *credentials.Manager InsecureRegistries []string @@ -34,7 +33,6 @@ type Config struct { } type Registry struct { - logger logging.Logger clientset kubernetes.Interface credentials *credentials.Manager insecureRegistries map[string]bool @@ -45,7 +43,7 @@ func New(cfg Config) *Registry { insecureRegistries := make(map[string]bool) for _, reg := range cfg.InsecureRegistries { insecureRegistries[reg] = true - cfg.Logger.Info("configured insecure registry", "registry", reg) + logger.Info("configured insecure registry", "registry", reg) } registryAliases := make(map[string]string) @@ -54,12 +52,11 @@ func New(cfg Config) *Registry { if len(parts) == 2 { from, to := parts[0], parts[1] registryAliases[from] = to - cfg.Logger.Info("configured registry alias", "from", from, "to", to) + logger.Info("configured registry alias", "from", from, "to", to) } } return &Registry{ - logger: cfg.Logger, clientset: cfg.Clientset, credentials: cfg.Credentials, insecureRegistries: insecureRegistries, @@ -96,7 +93,7 @@ func (r *Registry) GetImageConfig( if dockerConfig != nil { // Use credentials from our manager for registry, auth := range dockerConfig.Auths { - r.logger.Debug("using credentials from manager", + logger.Debug("using credentials from manager", "image", container.Image, "registry", registry, ) @@ -152,7 +149,7 @@ func (r *Registry) GetImageConfig( digest, found := r.findPlatformManifest(manifest.Manifests) if !found { - r.logger.Warn("no matching platform found in image index, using first manifest", + logger.Warn("no matching platform found in image index, using first manifest", "image", container.Image, "wanted_os", targetOS(), "wanted_arch", targetArch(), @@ -176,7 +173,7 @@ func (r *Registry) GetImageConfig( return nil, fmt.Errorf("failed to get image config: %w", err) } - r.logger.Debug("fetched image config", + logger.Debug("fetched image config", "image", container.Image, "entrypoint", configFile.Config.Entrypoint, "cmd", configFile.Config.Cmd, @@ -226,14 +223,14 @@ func (r *Registry) translateReference(ref name.Reference) (name.Reference, error // Check if we have an alias for this registry if newRegistry, hasAlias := r.registryAliases[currentRegistry]; hasAlias { targetRegistry = newRegistry - r.logger.Debug("translating registry alias", "from", currentRegistry, "to", targetRegistry) + logger.Debug("translating registry alias", "from", currentRegistry, "to", targetRegistry) } // Determine if target registry should use HTTP (insecure) var repoOpts []name.Option if r.insecureRegistries[targetRegistry] { repoOpts = append(repoOpts, name.Insecure) - r.logger.Debug("using insecure (HTTP) connection for registry", "registry", targetRegistry) + logger.Debug("using insecure (HTTP) connection for registry", "registry", targetRegistry) } // If no alias and no insecure flag needed, return original diff --git a/svc/preflight/routes/mutate/BUILD.bazel b/svc/preflight/routes/mutate/BUILD.bazel index 164633a7d7..fa3c60b240 100644 --- a/svc/preflight/routes/mutate/BUILD.bazel +++ b/svc/preflight/routes/mutate/BUILD.bazel @@ -6,7 +6,7 @@ go_library( importpath = "github.com/unkeyed/unkey/svc/preflight/routes/mutate", visibility = ["//visibility:public"], deps = [ - "//pkg/otel/logging", + "//pkg/logger", "//pkg/zen", "//svc/preflight/internal/services/mutator", "@io_k8s_api//admission/v1:admission", diff --git a/svc/preflight/routes/mutate/handler.go b/svc/preflight/routes/mutate/handler.go index 2553d0127a..41ff54c3b3 100644 --- a/svc/preflight/routes/mutate/handler.go +++ b/svc/preflight/routes/mutate/handler.go @@ -10,13 +10,12 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/zen" "github.com/unkeyed/unkey/svc/preflight/internal/services/mutator" ) type Handler struct { - Logger logging.Logger Mutator *mutator.Mutator } @@ -26,24 +25,24 @@ func (h *Handler) Path() string { return "/mutate" } func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { admissionReview, err := zen.BindBody[admissionv1.AdmissionReview](s) if err != nil { - h.Logger.Error("failed to parse admission review", "error", err) + logger.Error("failed to parse admission review", "error", err) return s.JSON(http.StatusBadRequest, map[string]string{"error": "failed to parse admission review"}) } if admissionReview.Request == nil { - h.Logger.Error("missing admission request") + logger.Error("missing admission request") return h.sendResponse(s, "", false, "missing admission request") } var pod corev1.Pod if err := json.Unmarshal(admissionReview.Request.Object.Raw, &pod); err != nil { - h.Logger.Error("failed to parse pod", "error", err) + logger.Error("failed to parse pod", "error", err) return h.sendResponse(s, admissionReview.Request.UID, false, "failed to parse pod") } namespace := admissionReview.Request.Namespace - h.Logger.Info("received admission request", + logger.Info("received admission request", "pod", pod.Name, "namespace", namespace, "uid", admissionReview.Request.UID, @@ -51,16 +50,16 @@ func (h *Handler) Handle(ctx context.Context, s *zen.Session) error { result, err := h.Mutator.Mutate(ctx, &pod, namespace) if err != nil { - h.Logger.Error("failed to mutate pod", "pod", pod.Name, "namespace", namespace, "error", err) + logger.Error("failed to mutate pod", "pod", pod.Name, "namespace", namespace, "error", err) return h.sendResponse(s, admissionReview.Request.UID, false, err.Error()) } if result.Mutated { - h.Logger.Info("mutated pod", "pod", pod.Name, "namespace", pod.Namespace, "message", result.Message) + logger.Info("mutated pod", "pod", pod.Name, "namespace", pod.Namespace, "message", result.Message) return h.sendResponseWithPatch(s, admissionReview.Request.UID, result.Patch) } - h.Logger.Info("skipped pod mutation", "pod", pod.Name, "namespace", pod.Namespace, "message", result.Message) + logger.Info("skipped pod mutation", "pod", pod.Name, "namespace", pod.Namespace, "message", result.Message) return h.sendResponse(s, admissionReview.Request.UID, true, result.Message) } diff --git a/svc/preflight/run.go b/svc/preflight/run.go index dcd1579285..fed4357d9e 100644 --- a/svc/preflight/run.go +++ b/svc/preflight/run.go @@ -3,13 +3,12 @@ package preflight import ( "context" "fmt" - "log/slog" "net" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/runner" "github.com/unkeyed/unkey/pkg/tls" "github.com/unkeyed/unkey/pkg/zen" @@ -25,8 +24,12 @@ func Run(ctx context.Context, cfg Config) error { return fmt.Errorf("bad config: %w", err) } - logger := logging.New().With(slog.String("service", "preflight")) - r := runner.New(logger) + logger.SetSampler(logger.TailSampler{ + SlowThreshold: cfg.LogSlowThreshold, + SampleRate: cfg.LogSampleRate, + }) + + r := runner.New() defer r.Recover() inClusterConfig, err := rest.InClusterConfig() @@ -43,15 +46,13 @@ func Run(ctx context.Context, cfg Config) error { var registries []credentials.Registry if cfg.DepotToken != "" { registries = append(registries, credentials.NewDepot(&credentials.DepotConfig{ - Logger: logger, - Token: cfg.DepotToken, + Token: cfg.DepotToken, })) logger.Info("depot registry configured for on-demand pull tokens") } credentialsManager := credentials.NewManager(registries...) reg := registry.New(registry.Config{ - Logger: logger, Clientset: clientset, Credentials: credentialsManager, InsecureRegistries: cfg.InsecureRegistries, @@ -65,8 +66,7 @@ func Run(ctx context.Context, cfg Config) error { //nolint:exhaustruct // zen.Config has many optional fields with sensible defaults server, err := zen.New(zen.Config{ - Logger: logger, - TLS: tlsConfig, + TLS: tlsConfig, }) if err != nil { return fmt.Errorf("failed to create server: %w", err) @@ -75,7 +75,6 @@ func Run(ctx context.Context, cfg Config) error { r.RegisterHealth(server.Mux()) m := mutator.New(mutator.Config{ - Logger: logger, Registry: reg, Clientset: clientset, Credentials: credentialsManager, @@ -85,18 +84,16 @@ func Run(ctx context.Context, cfg Config) error { }) middlewares := []zen.Middleware{ - zen.WithPanicRecovery(logger), - zen.WithLogging(logger), + zen.WithPanicRecovery(), + zen.WithLogging(), } server.RegisterRoute(middlewares, &mutate.Handler{ - Logger: logger, Mutator: m, }) // Start background cleanup of expired pull secrets cleanupService := cleanup.New(&cleanup.Config{ - Logger: logger, Clientset: clientset, }) diff --git a/svc/sentinel/BUILD.bazel b/svc/sentinel/BUILD.bazel index 9ebd29cba6..2f9243327f 100644 --- a/svc/sentinel/BUILD.bazel +++ b/svc/sentinel/BUILD.bazel @@ -13,8 +13,8 @@ go_library( "//pkg/clickhouse", "//pkg/clock", "//pkg/db", + "//pkg/logger", "//pkg/otel", - "//pkg/otel/logging", "//pkg/prometheus", "//pkg/runner", "//pkg/version", diff --git a/svc/sentinel/config.go b/svc/sentinel/config.go index cfd44bcca1..992ac4e0e9 100644 --- a/svc/sentinel/config.go +++ b/svc/sentinel/config.go @@ -3,6 +3,7 @@ package sentinel import ( "fmt" "slices" + "time" "github.com/unkeyed/unkey/pkg/assert" ) @@ -29,6 +30,14 @@ type Config struct { OtelEnabled bool OtelTraceSamplingRate float64 PrometheusPort int + + // --- Logging sampler configuration --- + + // LogSampleRate is the baseline probability (0.0-1.0) of emitting log events. + LogSampleRate float64 + + // LogSlowThreshold defines what duration qualifies as "slow" for sampling. + LogSlowThreshold time.Duration } func (c Config) Validate() error { diff --git a/svc/sentinel/middleware/BUILD.bazel b/svc/sentinel/middleware/BUILD.bazel index a7ef2ed147..c7c056a722 100644 --- a/svc/sentinel/middleware/BUILD.bazel +++ b/svc/sentinel/middleware/BUILD.bazel @@ -15,7 +15,7 @@ go_library( "//pkg/clock", "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/otel/tracing", "//pkg/zen", "//svc/sentinel/routes/proxy", diff --git a/svc/sentinel/middleware/observability.go b/svc/sentinel/middleware/observability.go index 2a0b5e35b8..500edd47a7 100644 --- a/svc/sentinel/middleware/observability.go +++ b/svc/sentinel/middleware/observability.go @@ -10,7 +10,7 @@ import ( "github.com/prometheus/client_golang/prometheus/promauto" "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" "github.com/unkeyed/unkey/pkg/zen" "go.opentelemetry.io/otel/attribute" @@ -172,7 +172,7 @@ func categorizeErrorType(urn codes.URN, statusCode int, hasError bool) string { return "none" } -func WithObservability(logger logging.Logger, environmentID, region string) zen.Middleware { +func WithObservability(environmentID, region string) zen.Middleware { return func(next zen.HandleFunc) zen.HandleFunc { return func(ctx context.Context, s *zen.Session) error { startTime := time.Now() diff --git a/svc/sentinel/routes/BUILD.bazel b/svc/sentinel/routes/BUILD.bazel index 57e7eb80ba..420f22c0db 100644 --- a/svc/sentinel/routes/BUILD.bazel +++ b/svc/sentinel/routes/BUILD.bazel @@ -11,7 +11,6 @@ go_library( deps = [ "//pkg/clickhouse", "//pkg/clock", - "//pkg/otel/logging", "//pkg/zen", "//svc/sentinel/middleware", "//svc/sentinel/routes/internal_health", diff --git a/svc/sentinel/routes/internal_health/BUILD.bazel b/svc/sentinel/routes/internal_health/BUILD.bazel index 50914bd0ab..f10d4b34eb 100644 --- a/svc/sentinel/routes/internal_health/BUILD.bazel +++ b/svc/sentinel/routes/internal_health/BUILD.bazel @@ -5,8 +5,5 @@ go_library( srcs = ["handler.go"], importpath = "github.com/unkeyed/unkey/svc/sentinel/routes/internal_health", visibility = ["//visibility:public"], - deps = [ - "//pkg/otel/logging", - "//pkg/zen", - ], + deps = ["//pkg/zen"], ) diff --git a/svc/sentinel/routes/internal_health/handler.go b/svc/sentinel/routes/internal_health/handler.go index 3b02907f75..63112c26de 100644 --- a/svc/sentinel/routes/internal_health/handler.go +++ b/svc/sentinel/routes/internal_health/handler.go @@ -3,13 +3,10 @@ package handler import ( "context" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/zen" ) -type Handler struct { - Logger logging.Logger -} +type Handler struct{} func (h *Handler) Method() string { return "GET" diff --git a/svc/sentinel/routes/proxy/BUILD.bazel b/svc/sentinel/routes/proxy/BUILD.bazel index 8082ec9dd4..16f24a470f 100644 --- a/svc/sentinel/routes/proxy/BUILD.bazel +++ b/svc/sentinel/routes/proxy/BUILD.bazel @@ -12,7 +12,7 @@ go_library( "//pkg/clock", "//pkg/codes", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/timing", "//pkg/uid", "//pkg/zen", diff --git a/svc/sentinel/routes/proxy/handler.go b/svc/sentinel/routes/proxy/handler.go index ccbc9b26c7..79971594fb 100644 --- a/svc/sentinel/routes/proxy/handler.go +++ b/svc/sentinel/routes/proxy/handler.go @@ -12,7 +12,7 @@ import ( "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/timing" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/pkg/zen" @@ -20,7 +20,6 @@ import ( ) type Handler struct { - Logger logging.Logger RouterService router.Service Clock clock.Clock Transport *http.Transport @@ -42,7 +41,7 @@ func (h *Handler) Handle(ctx context.Context, sess *zen.Session) error { tracking, ok := SentinelTrackingFromContext(ctx) if !ok { - h.Logger.Warn("no sentinel tracking context found") + logger.Warn("no sentinel tracking context found") } requestID := uid.New("req") @@ -97,7 +96,7 @@ func (h *Handler) Handle(ctx context.Context, sess *zen.Session) error { targetURL, err := url.Parse("http://" + instance.Address) if err != nil { - h.Logger.Error("invalid instance address", "address", instance.Address, "error", err) + logger.Error("invalid instance address", "address", instance.Address, "error", err) return fault.Wrap(err, fault.Code(codes.Sentinel.Internal.InvalidConfiguration.URN()), fault.Internal("invalid service address"), diff --git a/svc/sentinel/routes/register.go b/svc/sentinel/routes/register.go index 4120d597bf..eda0d2d03d 100644 --- a/svc/sentinel/routes/register.go +++ b/svc/sentinel/routes/register.go @@ -12,11 +12,11 @@ import ( ) func Register(srv *zen.Server, svc *Services) { - withPanicRecovery := zen.WithPanicRecovery(svc.Logger) - withObservability := middleware.WithObservability(svc.Logger, svc.EnvironmentID, svc.Region) + withPanicRecovery := zen.WithPanicRecovery() + withObservability := middleware.WithObservability(svc.EnvironmentID, svc.Region) withSentinelLogging := middleware.WithSentinelLogging(svc.ClickHouse, svc.Clock, svc.SentinelID, svc.Region) withProxyErrorHandling := middleware.WithProxyErrorHandling() - withLogging := zen.WithLogging(svc.Logger) + withLogging := zen.WithLogging() withTimeout := zen.WithTimeout(5 * time.Minute) defaultMiddlewares := []zen.Middleware{ @@ -30,9 +30,7 @@ func Register(srv *zen.Server, svc *Services) { srv.RegisterRoute( []zen.Middleware{withLogging}, - &internalHealth.Handler{ - Logger: svc.Logger, - }, + &internalHealth.Handler{}, ) //nolint:exhaustruct @@ -50,7 +48,6 @@ func Register(srv *zen.Server, svc *Services) { srv.RegisterRoute( defaultMiddlewares, &proxy.Handler{ - Logger: svc.Logger, RouterService: svc.RouterService, Clock: svc.Clock, Transport: transport, diff --git a/svc/sentinel/routes/services.go b/svc/sentinel/routes/services.go index ea461548c3..f4fd40d633 100644 --- a/svc/sentinel/routes/services.go +++ b/svc/sentinel/routes/services.go @@ -3,13 +3,11 @@ package routes import ( "github.com/unkeyed/unkey/pkg/clickhouse" "github.com/unkeyed/unkey/pkg/clock" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/svc/sentinel/services/router" ) // Services contains all dependencies needed by route handlers type Services struct { - Logger logging.Logger RouterService router.Service Clock clock.Clock WorkspaceID string diff --git a/svc/sentinel/run.go b/svc/sentinel/run.go index 5b7ef114b6..4d38a7b7d1 100644 --- a/svc/sentinel/run.go +++ b/svc/sentinel/run.go @@ -10,8 +10,8 @@ import ( "github.com/unkeyed/unkey/pkg/clickhouse" "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/db" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/prometheus" "github.com/unkeyed/unkey/pkg/runner" "github.com/unkeyed/unkey/pkg/version" @@ -29,6 +29,11 @@ func Run(ctx context.Context, cfg Config) error { return fmt.Errorf("bad config: %w", err) } + logger.SetSampler(logger.TailSampler{ + SlowThreshold: cfg.LogSlowThreshold, + SampleRate: cfg.LogSampleRate, + }) + clk := clock.New() // Initialize OTEL before creating logger so the logger picks up the OTLP handler @@ -46,34 +51,22 @@ func Run(ctx context.Context, cfg Config) error { } } - // Create logger after InitGrafana so it picks up the OTLP handler - logger := logging.New() - if cfg.SentinelID != "" { - logger = logger.With(slog.String("sentinelID", cfg.SentinelID)) - } - - logger = logger.With( + // Add base attributes to global logger + logger.AddBaseAttrs(slog.GroupAttrs("instance", + slog.String("sentinelID", cfg.SentinelID), slog.String("workspaceID", cfg.WorkspaceID), slog.String("environmentID", cfg.EnvironmentID), - ) + slog.String("region", cfg.Region), + slog.String("version", version.Version), + )) - if cfg.Region != "" { - logger = logger.With(slog.String("region", cfg.Region)) - } - - if version.Version != "" { - logger = logger.With(slog.String("version", version.Version)) - } - - r := runner.New(logger) + r := runner.New() defer r.Recover() r.DeferCtx(shutdownGrafana) if cfg.PrometheusPort > 0 { - prom, promErr := prometheus.New(prometheus.Config{ - Logger: logger, - }) + prom, promErr := prometheus.New() if promErr != nil { return fmt.Errorf("unable to start prometheus: %w", promErr) } @@ -96,7 +89,6 @@ func Run(ctx context.Context, cfg Config) error { database, err := db.New(db.Config{ PrimaryDSN: cfg.DatabasePrimary, ReadOnlyDSN: cfg.DatabaseReadonlyReplica, - Logger: logger, }) if err != nil { return fmt.Errorf("unable to create db: %w", err) @@ -106,8 +98,7 @@ func Run(ctx context.Context, cfg Config) error { var ch clickhouse.ClickHouse = clickhouse.NewNoop() if cfg.ClickhouseURL != "" { ch, err = clickhouse.New(clickhouse.Config{ - URL: cfg.ClickhouseURL, - Logger: logger, + URL: cfg.ClickhouseURL, }) if err != nil { return fmt.Errorf("unable to create clickhouse: %w", err) @@ -116,7 +107,6 @@ func Run(ctx context.Context, cfg Config) error { } routerSvc, err := router.New(router.Config{ - Logger: logger, DB: database, Clock: clk, EnvironmentID: cfg.EnvironmentID, @@ -127,7 +117,6 @@ func Run(ctx context.Context, cfg Config) error { } svcs := &routes.Services{ - Logger: logger, RouterService: routerSvc, Clock: clk, WorkspaceID: cfg.WorkspaceID, @@ -139,7 +128,6 @@ func Run(ctx context.Context, cfg Config) error { } srv, err := zen.New(zen.Config{ - Logger: logger, TLS: nil, Flags: nil, EnableH2C: true, diff --git a/svc/sentinel/services/router/BUILD.bazel b/svc/sentinel/services/router/BUILD.bazel index 386e91ae47..623512f5e4 100644 --- a/svc/sentinel/services/router/BUILD.bazel +++ b/svc/sentinel/services/router/BUILD.bazel @@ -16,6 +16,6 @@ go_library( "//pkg/codes", "//pkg/db", "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", ], ) diff --git a/svc/sentinel/services/router/interface.go b/svc/sentinel/services/router/interface.go index 6dd6600a98..71cd0ad238 100644 --- a/svc/sentinel/services/router/interface.go +++ b/svc/sentinel/services/router/interface.go @@ -5,7 +5,6 @@ import ( "github.com/unkeyed/unkey/pkg/clock" "github.com/unkeyed/unkey/pkg/db" - "github.com/unkeyed/unkey/pkg/otel/logging" ) type Service interface { @@ -14,7 +13,6 @@ type Service interface { } type Config struct { - Logger logging.Logger DB db.Database Clock clock.Clock EnvironmentID string diff --git a/svc/sentinel/services/router/service.go b/svc/sentinel/services/router/service.go index 9f1494ee1a..f1b1365812 100644 --- a/svc/sentinel/services/router/service.go +++ b/svc/sentinel/services/router/service.go @@ -12,13 +12,12 @@ import ( "github.com/unkeyed/unkey/pkg/codes" "github.com/unkeyed/unkey/pkg/db" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) var _ Service = (*service)(nil) type service struct { - logger logging.Logger db db.Database clock clock.Clock environmentID string @@ -30,7 +29,6 @@ type service struct { func New(cfg Config) (*service, error) { deploymentCache, err := cache.New[string, db.Deployment](cache.Config[string, db.Deployment]{ - Logger: cfg.Logger, Resource: "deployment", Clock: cfg.Clock, MaxSize: 1000, @@ -43,7 +41,6 @@ func New(cfg Config) (*service, error) { instancesCache, err := cache.New[string, []db.Instance](cache.Config[string, []db.Instance]{ Clock: cfg.Clock, - Logger: cfg.Logger, Resource: "instance", MaxSize: 1000, Fresh: 10 * time.Second, @@ -54,7 +51,6 @@ func New(cfg Config) (*service, error) { } return &service{ - logger: cfg.Logger, db: cfg.DB, clock: cfg.Clock, environmentID: cfg.EnvironmentID, @@ -85,7 +81,7 @@ func (s *service) GetDeployment(ctx context.Context, deploymentID string) (db.De } if deployment.EnvironmentID != s.environmentID { - s.logger.Warn("deployment does not belong to this environment", + logger.Warn("deployment does not belong to this environment", "deploymentID", deploymentID, "deploymentEnv", deployment.EnvironmentID, "sentinelEnv", s.environmentID, diff --git a/svc/vault/BUILD.bazel b/svc/vault/BUILD.bazel index f4ed8d1e61..95556406c6 100644 --- a/svc/vault/BUILD.bazel +++ b/svc/vault/BUILD.bazel @@ -11,8 +11,8 @@ go_library( deps = [ "//gen/proto/vault/v1/vaultv1connect", "//pkg/assert", + "//pkg/logger", "//pkg/otel", - "//pkg/otel/logging", "//pkg/runner", "//pkg/version", "//svc/vault/internal/storage", diff --git a/svc/vault/config.go b/svc/vault/config.go index 905e071337..2c4ac2ad9e 100644 --- a/svc/vault/config.go +++ b/svc/vault/config.go @@ -1,6 +1,10 @@ package vault -import "github.com/unkeyed/unkey/pkg/assert" +import ( + "time" + + "github.com/unkeyed/unkey/pkg/assert" +) type Config struct { // InstanceID is the unique identifier for this instance of the API server @@ -33,6 +37,14 @@ type Config struct { MasterKeys []string // BearerToken is the authentication token for securing vault operations BearerToken string + + // --- Logging sampler configuration --- + + // LogSampleRate is the baseline probability (0.0-1.0) of emitting log events. + LogSampleRate float64 + + // LogSlowThreshold defines what duration qualifies as "slow" for sampling. + LogSlowThreshold time.Duration } func (c Config) Validate() error { diff --git a/svc/vault/integration/BUILD.bazel b/svc/vault/integration/BUILD.bazel index e1a89d23e6..4b893d4b1e 100644 --- a/svc/vault/integration/BUILD.bazel +++ b/svc/vault/integration/BUILD.bazel @@ -12,7 +12,6 @@ go_test( deps = [ "//gen/proto/vault/v1:vault", "//pkg/dockertest", - "//pkg/otel/logging", "//pkg/uid", "//svc/vault/internal/keys", "//svc/vault/internal/storage", diff --git a/svc/vault/integration/coldstart_test.go b/svc/vault/integration/coldstart_test.go index 417ec325b6..3ad12b245b 100644 --- a/svc/vault/integration/coldstart_test.go +++ b/svc/vault/integration/coldstart_test.go @@ -8,7 +8,6 @@ import ( "github.com/stretchr/testify/require" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" "github.com/unkeyed/unkey/pkg/dockertest" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/svc/vault/internal/keys" "github.com/unkeyed/unkey/svc/vault/internal/storage" @@ -28,14 +27,11 @@ func Test_ColdStart(t *testing.T) { s3 := dockertest.S3(t) - logger := logging.NewNoop() - storage, err := storage.NewS3(storage.S3Config{ S3URL: s3.URL, S3Bucket: "test", S3AccessKeyID: s3.AccessKeyID, S3AccessKeySecret: s3.SecretAccessKey, - Logger: logger, }) require.NoError(t, err) @@ -44,7 +40,6 @@ func Test_ColdStart(t *testing.T) { v, err := vault.New(vault.Config{ Storage: storage, - Logger: logger, MasterKeys: []string{masterKey}, BearerToken: "test-bearer-token", }) diff --git a/svc/vault/integration/migrate_deks_test.go b/svc/vault/integration/migrate_deks_test.go index 60ab6d6282..cad1b56daf 100644 --- a/svc/vault/integration/migrate_deks_test.go +++ b/svc/vault/integration/migrate_deks_test.go @@ -9,7 +9,6 @@ import ( "github.com/stretchr/testify/require" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" "github.com/unkeyed/unkey/pkg/dockertest" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/svc/vault/internal/keys" "github.com/unkeyed/unkey/svc/vault/internal/storage" @@ -27,7 +26,6 @@ import ( // when the master key is rotated. func TestMigrateDeks(t *testing.T) { - logger := logging.NewNoop() data := make(map[string]string) bearerToken := "integration-test-token" s3 := dockertest.S3(t) @@ -37,7 +35,6 @@ func TestMigrateDeks(t *testing.T) { S3Bucket: "test", S3AccessKeyID: s3.AccessKeyID, S3AccessKeySecret: s3.SecretAccessKey, - Logger: logger, }) require.NoError(t, err) @@ -46,7 +43,6 @@ func TestMigrateDeks(t *testing.T) { v, err := vault.New(vault.Config{ Storage: storage, - Logger: logger, MasterKeys: []string{masterKeyOld}, BearerToken: bearerToken, }) @@ -82,7 +78,6 @@ func TestMigrateDeks(t *testing.T) { v, err = vault.New(vault.Config{ Storage: storage, - Logger: logger, MasterKeys: []string{masterKeyNew, masterKeyOld}, BearerToken: bearerToken, }) diff --git a/svc/vault/integration/reencryption_test.go b/svc/vault/integration/reencryption_test.go index 15e02dcf51..7f1188a007 100644 --- a/svc/vault/integration/reencryption_test.go +++ b/svc/vault/integration/reencryption_test.go @@ -11,7 +11,6 @@ import ( "github.com/stretchr/testify/require" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" "github.com/unkeyed/unkey/pkg/dockertest" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/svc/vault/internal/keys" "github.com/unkeyed/unkey/svc/vault/internal/storage" @@ -28,8 +27,6 @@ import ( // - Old ciphertexts remain valid after DEK rotation func TestReEncrypt(t *testing.T) { - logger := logging.NewNoop() - s3 := dockertest.S3(t) storage, err := storage.NewS3(storage.S3Config{ @@ -37,7 +34,6 @@ func TestReEncrypt(t *testing.T) { S3Bucket: "vault", S3AccessKeyID: s3.AccessKeyID, S3AccessKeySecret: s3.SecretAccessKey, - Logger: logger, }) require.NoError(t, err) @@ -48,7 +44,6 @@ func TestReEncrypt(t *testing.T) { v, err := vault.New(vault.Config{ Storage: storage, - Logger: logger, MasterKeys: []string{masterKey}, BearerToken: bearer, }) diff --git a/svc/vault/integration/reusing_deks_test.go b/svc/vault/integration/reusing_deks_test.go index c8cadcf54d..61cb626594 100644 --- a/svc/vault/integration/reusing_deks_test.go +++ b/svc/vault/integration/reusing_deks_test.go @@ -11,7 +11,6 @@ import ( "github.com/stretchr/testify/require" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" "github.com/unkeyed/unkey/pkg/dockertest" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/svc/vault/internal/keys" "github.com/unkeyed/unkey/svc/vault/internal/storage" @@ -26,8 +25,6 @@ import ( // it is explicitly rotated. func TestReuseDEKsForSameKeyring(t *testing.T) { - logger := logging.NewNoop() - s3 := dockertest.S3(t) storage, err := storage.NewS3(storage.S3Config{ @@ -35,7 +32,6 @@ func TestReuseDEKsForSameKeyring(t *testing.T) { S3Bucket: fmt.Sprintf("%d", time.Now().UnixMilli()), S3AccessKeyID: s3.AccessKeyID, S3AccessKeySecret: s3.SecretAccessKey, - Logger: logger, }) require.NoError(t, err) @@ -46,7 +42,6 @@ func TestReuseDEKsForSameKeyring(t *testing.T) { v, err := vault.New(vault.Config{ Storage: storage, - Logger: logger, MasterKeys: []string{masterKey}, BearerToken: bearer, }) @@ -78,8 +73,6 @@ func TestReuseDEKsForSameKeyring(t *testing.T) { // affect other keyrings. func TestIndividualDEKsPerKeyring(t *testing.T) { - logger := logging.NewNoop() - s3 := dockertest.S3(t) storage, err := storage.NewS3(storage.S3Config{ @@ -87,7 +80,6 @@ func TestIndividualDEKsPerKeyring(t *testing.T) { S3Bucket: fmt.Sprintf("%d", time.Now().UnixMilli()), S3AccessKeyID: s3.AccessKeyID, S3AccessKeySecret: s3.SecretAccessKey, - Logger: logger, }) require.NoError(t, err) @@ -97,7 +89,6 @@ func TestIndividualDEKsPerKeyring(t *testing.T) { v, err := vault.New(vault.Config{ Storage: storage, - Logger: logger, MasterKeys: []string{masterKey}, BearerToken: bearer, }) diff --git a/svc/vault/internal/keyring/BUILD.bazel b/svc/vault/internal/keyring/BUILD.bazel index dd8c46e83b..48b641dbf7 100644 --- a/svc/vault/internal/keyring/BUILD.bazel +++ b/svc/vault/internal/keyring/BUILD.bazel @@ -17,7 +17,7 @@ go_library( deps = [ "//gen/proto/vault/v1:vault", "//pkg/encryption", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/otel/tracing", "//svc/vault/internal/keys", "//svc/vault/internal/storage", @@ -34,7 +34,6 @@ go_test( deps = [ "//gen/proto/vault/v1:vault", "//pkg/fuzz", - "//pkg/otel/logging", "//svc/vault/internal/storage", "@com_github_stretchr_testify//require", "@org_golang_google_protobuf//proto", diff --git a/svc/vault/internal/keyring/fuzz_test.go b/svc/vault/internal/keyring/fuzz_test.go index de6fab9169..b4970ecd53 100644 --- a/svc/vault/internal/keyring/fuzz_test.go +++ b/svc/vault/internal/keyring/fuzz_test.go @@ -10,7 +10,6 @@ import ( "github.com/stretchr/testify/require" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" "github.com/unkeyed/unkey/pkg/fuzz" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/svc/vault/internal/storage" "google.golang.org/protobuf/proto" ) @@ -35,14 +34,11 @@ func setupTestKeyring(t *testing.T) *Keyring { CreatedAt: time.Now().UnixMilli(), } - store, err := storage.NewMemory(storage.MemoryConfig{ - Logger: logging.NewNoop(), - }) + store, err := storage.NewMemory() require.NoError(t, err) kr, err := New(Config{ Store: store, - Logger: logging.NewNoop(), EncryptionKey: kek, DecryptionKeys: map[string]*vaultv1.KeyEncryptionKey{ kek.GetId(): kek, @@ -224,14 +220,11 @@ func FuzzDecodeWithWrongKEK(f *testing.F) { kekA.Key[i] = byte(i) } - storeA, err := storage.NewMemory(storage.MemoryConfig{ - Logger: logging.NewNoop(), - }) + storeA, err := storage.NewMemory() require.NoError(t, err) krA, err := New(Config{ Store: storeA, - Logger: logging.NewNoop(), EncryptionKey: kekA, DecryptionKeys: map[string]*vaultv1.KeyEncryptionKey{ kekA.GetId(): kekA, @@ -249,14 +242,11 @@ func FuzzDecodeWithWrongKEK(f *testing.F) { kekB.Key[i] = byte(255 - i) } - storeB, err := storage.NewMemory(storage.MemoryConfig{ - Logger: logging.NewNoop(), - }) + storeB, err := storage.NewMemory() require.NoError(t, err) krB, err := New(Config{ Store: storeB, - Logger: logging.NewNoop(), EncryptionKey: kekB, DecryptionKeys: map[string]*vaultv1.KeyEncryptionKey{ kekB.GetId(): kekB, diff --git a/svc/vault/internal/keyring/keyring.go b/svc/vault/internal/keyring/keyring.go index fbeeab64f7..8cc134a320 100644 --- a/svc/vault/internal/keyring/keyring.go +++ b/svc/vault/internal/keyring/keyring.go @@ -4,13 +4,11 @@ import ( "fmt" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/svc/vault/internal/storage" ) type Keyring struct { - store storage.Storage - logger logging.Logger + store storage.Storage // any of these can be used for decryption decryptionKeys map[string]*vaultv1.KeyEncryptionKey @@ -18,8 +16,7 @@ type Keyring struct { } type Config struct { - Store storage.Storage - Logger logging.Logger + Store storage.Storage DecryptionKeys map[string]*vaultv1.KeyEncryptionKey EncryptionKey *vaultv1.KeyEncryptionKey @@ -29,7 +26,6 @@ func New(config Config) (*Keyring, error) { return &Keyring{ store: config.Store, - logger: config.Logger, encryptionKey: config.EncryptionKey, decryptionKeys: config.DecryptionKeys, }, nil diff --git a/svc/vault/internal/keyring/roll_keys.go b/svc/vault/internal/keyring/roll_keys.go index 19b4d7efe5..b94bc78907 100644 --- a/svc/vault/internal/keyring/roll_keys.go +++ b/svc/vault/internal/keyring/roll_keys.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" "github.com/unkeyed/unkey/svc/vault/internal/storage" ) @@ -30,7 +31,7 @@ func (k *Keyring) RollKeys(ctx context.Context, ringID string) error { return fmt.Errorf("failed to decode and decrypt key: %w", err) } if encryptionKeyId == k.encryptionKey.GetId() { - k.logger.Info("key already encrypted with latest kek", + logger.Info("key already encrypted with latest kek", "keyId", dek.GetId(), ) continue diff --git a/svc/vault/internal/storage/BUILD.bazel b/svc/vault/internal/storage/BUILD.bazel index ac966bfca2..4a77e1b977 100644 --- a/svc/vault/internal/storage/BUILD.bazel +++ b/svc/vault/internal/storage/BUILD.bazel @@ -11,7 +11,7 @@ go_library( visibility = ["//svc/vault:__subpackages__"], deps = [ "//pkg/fault", - "//pkg/otel/logging", + "//pkg/logger", "@com_github_aws_aws_sdk_go_v2//aws", "@com_github_aws_aws_sdk_go_v2_config//:config", "@com_github_aws_aws_sdk_go_v2_credentials//:credentials", @@ -28,7 +28,6 @@ go_test( embed = [":storage"], deps = [ "//pkg/dockertest", - "//pkg/otel/logging", "@com_github_stretchr_testify//assert", "@com_github_stretchr_testify//require", ], @@ -41,7 +40,6 @@ go_test( embed = [":storage"], deps = [ "//pkg/dockertest", - "//pkg/otel/logging", "@com_github_stretchr_testify//require", ], ) diff --git a/svc/vault/internal/storage/memory.go b/svc/vault/internal/storage/memory.go index ff54bf824a..de1abcb6b2 100644 --- a/svc/vault/internal/storage/memory.go +++ b/svc/vault/internal/storage/memory.go @@ -5,30 +5,18 @@ import ( "fmt" "strings" "sync" - - "github.com/unkeyed/unkey/pkg/otel/logging" ) // memory is an in-memory storage implementation for testing purposes. type memory struct { - config MemoryConfig - mu sync.RWMutex - data map[string][]byte - logger logging.Logger -} - -type MemoryConfig struct { - Logger logging.Logger + mu sync.RWMutex + data map[string][]byte } -func NewMemory(config MemoryConfig) (Storage, error) { - logger := config.Logger.With("service", "storage") - +func NewMemory() (Storage, error) { return &memory{ - config: config, - logger: logger, - data: make(map[string][]byte), - mu: sync.RWMutex{}, + data: make(map[string][]byte), + mu: sync.RWMutex{}, }, nil } diff --git a/svc/vault/internal/storage/memory_test.go b/svc/vault/internal/storage/memory_test.go index 8cc72b63ce..071d855b16 100644 --- a/svc/vault/internal/storage/memory_test.go +++ b/svc/vault/internal/storage/memory_test.go @@ -7,7 +7,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // TestMemory_PutAndGet verifies basic put and get operations. @@ -323,8 +322,7 @@ func TestMemory_DataIsolation(t *testing.T) { // newTestMemoryStorage creates a new memory storage for testing. func newTestMemoryStorage(t *testing.T) Storage { t.Helper() - logger := logging.NewNoop() - store, err := NewMemory(MemoryConfig{Logger: logger}) + store, err := NewMemory() require.NoError(t, err) return store } diff --git a/svc/vault/internal/storage/s3.go b/svc/vault/internal/storage/s3.go index 0f7a9a1e19..4d99dc94f8 100644 --- a/svc/vault/internal/storage/s3.go +++ b/svc/vault/internal/storage/s3.go @@ -13,13 +13,12 @@ import ( awsS3 "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/unkeyed/unkey/pkg/fault" - "github.com/unkeyed/unkey/pkg/otel/logging" + "github.com/unkeyed/unkey/pkg/logger" ) type s3 struct { client *awsS3.Client config S3Config - logger logging.Logger } type S3Config struct { @@ -27,12 +26,9 @@ type S3Config struct { S3Bucket string S3AccessKeyID string S3AccessKeySecret string - Logger logging.Logger } func NewS3(config S3Config) (Storage, error) { - logger := config.Logger.With("service", "storage") - logger.Info("using s3 storage") // nolint:staticcheck @@ -56,7 +52,6 @@ func NewS3(config S3Config) (Storage, error) { } client := awsS3.NewFromConfig(cfg) - logger.Info("creating bucket if necessary") _, err = client.CreateBucket(context.Background(), &awsS3.CreateBucketInput{ Bucket: aws.String(config.S3Bucket), }) @@ -66,7 +61,7 @@ func NewS3(config S3Config) (Storage, error) { logger.Info("s3 storage initialized") - return &s3{config: config, client: client, logger: logger}, nil + return &s3{config: config, client: client}, nil } func (s *s3) Key(workspaceId string, dekID string) string { diff --git a/svc/vault/internal/storage/s3_test.go b/svc/vault/internal/storage/s3_test.go index d2ca98dba8..94f49a15ed 100644 --- a/svc/vault/internal/storage/s3_test.go +++ b/svc/vault/internal/storage/s3_test.go @@ -9,7 +9,6 @@ import ( "github.com/stretchr/testify/require" "github.com/unkeyed/unkey/pkg/dockertest" - "github.com/unkeyed/unkey/pkg/otel/logging" ) // TestS3_PutAndGet verifies basic put and get operations against real S3. @@ -310,7 +309,6 @@ func newTestS3Storage(t *testing.T) Storage { t.Helper() s3Config := dockertest.S3(t) - logger := logging.NewNoop() // Use a unique bucket name per test to ensure isolation bucketName := fmt.Sprintf("test-%d", time.Now().UnixNano()) @@ -320,7 +318,6 @@ func newTestS3Storage(t *testing.T) Storage { S3Bucket: bucketName, S3AccessKeyID: s3Config.AccessKeyID, S3AccessKeySecret: s3Config.SecretAccessKey, - Logger: logger, }) require.NoError(t, err) diff --git a/svc/vault/internal/vault/BUILD.bazel b/svc/vault/internal/vault/BUILD.bazel index 423a4b99fd..c62787e00e 100644 --- a/svc/vault/internal/vault/BUILD.bazel +++ b/svc/vault/internal/vault/BUILD.bazel @@ -22,7 +22,7 @@ go_library( "//pkg/cache/middleware", "//pkg/clock", "//pkg/encryption", - "//pkg/otel/logging", + "//pkg/logger", "//pkg/otel/tracing", "//svc/vault/internal/keyring", "//svc/vault/internal/storage", @@ -60,7 +60,6 @@ go_test( deps = [ "//gen/proto/vault/v1:vault", "//pkg/fuzz", - "//pkg/otel/logging", "//pkg/uid", "//svc/vault/internal/keys", "//svc/vault/internal/storage", diff --git a/svc/vault/internal/vault/roll_deks.go b/svc/vault/internal/vault/roll_deks.go index 80fb4e8cf4..398b120812 100644 --- a/svc/vault/internal/vault/roll_deks.go +++ b/svc/vault/internal/vault/roll_deks.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" "github.com/unkeyed/unkey/svc/vault/internal/storage" ) @@ -29,7 +30,7 @@ func (s *Service) RollDeks(ctx context.Context) error { return fmt.Errorf("failed to decode and decrypt key: %w", err) } if kekID == s.encryptionKey.GetId() { - s.logger.Info("key already encrypted with latest kek", + logger.Info("key already encrypted with latest kek", "dekId", dek.GetId(), ) continue diff --git a/svc/vault/internal/vault/rpc_reencrypt.go b/svc/vault/internal/vault/rpc_reencrypt.go index 978f935398..c300150d98 100644 --- a/svc/vault/internal/vault/rpc_reencrypt.go +++ b/svc/vault/internal/vault/rpc_reencrypt.go @@ -6,6 +6,7 @@ import ( "connectrpc.com/connect" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel/tracing" ) @@ -15,7 +16,7 @@ func (s *Service) ReEncrypt(ctx context.Context, req *connect.Request[vaultv1.Re } ctx, span := tracing.Start(ctx, "vault.ReEncrypt") defer span.End() - s.logger.Info("reencrypting", + logger.Info("reencrypting", "keyring", req.Msg.GetKeyring(), ) diff --git a/svc/vault/internal/vault/service.go b/svc/vault/internal/vault/service.go index ecc5cc8b63..212edbb737 100644 --- a/svc/vault/internal/vault/service.go +++ b/svc/vault/internal/vault/service.go @@ -10,7 +10,6 @@ import ( "github.com/unkeyed/unkey/pkg/cache" cacheMiddleware "github.com/unkeyed/unkey/pkg/cache/middleware" "github.com/unkeyed/unkey/pkg/clock" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/svc/vault/internal/keyring" "github.com/unkeyed/unkey/svc/vault/internal/storage" "google.golang.org/protobuf/proto" @@ -19,7 +18,6 @@ import ( const LATEST = "LATEST" type Service struct { - logger logging.Logger keyCache cache.Cache[string, *vaultv1.DataEncryptionKey] storage storage.Storage @@ -34,7 +32,6 @@ type Service struct { var _ vaultv1connect.VaultServiceHandler = (*Service)(nil) type Config struct { - Logger logging.Logger Storage storage.Storage MasterKeys []string BearerToken string @@ -50,7 +47,6 @@ func New(cfg Config) (*Service, error) { kr, err := keyring.New(keyring.Config{ Store: cfg.Storage, - Logger: cfg.Logger, DecryptionKeys: decryptionKeys, EncryptionKey: encryptionKey, }) @@ -62,7 +58,6 @@ func New(cfg Config) (*Service, error) { Fresh: time.Hour, Stale: 24 * time.Hour, MaxSize: 10000, - Logger: cfg.Logger, Resource: "data_encryption_key", Clock: clock.New(), }) @@ -71,7 +66,6 @@ func New(cfg Config) (*Service, error) { } return &Service{ - logger: cfg.Logger, storage: cfg.Storage, keyCache: cacheMiddleware.WithTracing(cache), decryptionKeys: decryptionKeys, diff --git a/svc/vault/internal/vault/service_test.go b/svc/vault/internal/vault/service_test.go index e5b6e57942..26f0fa001f 100644 --- a/svc/vault/internal/vault/service_test.go +++ b/svc/vault/internal/vault/service_test.go @@ -4,19 +4,15 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/svc/vault/internal/keys" "github.com/unkeyed/unkey/svc/vault/internal/storage" ) func setupTestService(t *testing.T) *Service { - logger := logging.NewNoop() // Use memory storage for fast, isolated tests - memoryStorage, err := storage.NewMemory(storage.MemoryConfig{ - Logger: logger, - }) + memoryStorage, err := storage.NewMemory() require.NoError(t, err) _, masterKey, err := keys.GenerateMasterKey() @@ -26,7 +22,6 @@ func setupTestService(t *testing.T) *Service { bearerToken := "test-token-" + uid.New("test") service, err := New(Config{ - Logger: logger, Storage: memoryStorage, MasterKeys: []string{masterKey}, BearerToken: bearerToken, diff --git a/svc/vault/internal/vault/storage_corruption_test.go b/svc/vault/internal/vault/storage_corruption_test.go index 9135013ed3..b9ffaca7aa 100644 --- a/svc/vault/internal/vault/storage_corruption_test.go +++ b/svc/vault/internal/vault/storage_corruption_test.go @@ -8,7 +8,6 @@ import ( "connectrpc.com/connect" "github.com/stretchr/testify/require" vaultv1 "github.com/unkeyed/unkey/gen/proto/vault/v1" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/uid" "github.com/unkeyed/unkey/svc/vault/internal/keys" "github.com/unkeyed/unkey/svc/vault/internal/storage" @@ -22,8 +21,7 @@ type corruptibleStorage struct { } func newCorruptibleStorage(t *testing.T) *corruptibleStorage { - logger := logging.NewNoop() - mem, err := storage.NewMemory(storage.MemoryConfig{Logger: logger}) + mem, err := storage.NewMemory() require.NoError(t, err) return &corruptibleStorage{ Storage: mem, @@ -49,7 +47,6 @@ func (s *corruptibleStorage) CorruptKey(key string, data []byte) { // the vault must detect this and return a clear error, not silently return // wrong data. func TestStorageCorruption_CorruptedDEK(t *testing.T) { - logger := logging.NewNoop() corruptibleStore := newCorruptibleStorage(t) _, masterKey, err := keys.GenerateMasterKey() @@ -57,7 +54,6 @@ func TestStorageCorruption_CorruptedDEK(t *testing.T) { bearerToken := "test-token-" + uid.New("test") service, err := New(Config{ - Logger: logger, Storage: corruptibleStore, MasterKeys: []string{masterKey}, BearerToken: bearerToken, @@ -110,7 +106,6 @@ func TestStorageCorruption_CorruptedDEK(t *testing.T) { // TestStorageCorruption_EmptyDEK verifies that empty DEK data in storage is // handled gracefully. func TestStorageCorruption_EmptyDEK(t *testing.T) { - logger := logging.NewNoop() corruptibleStore := newCorruptibleStorage(t) _, masterKey, err := keys.GenerateMasterKey() @@ -118,7 +113,6 @@ func TestStorageCorruption_EmptyDEK(t *testing.T) { bearerToken := "test-token-" + uid.New("test") service, err := New(Config{ - Logger: logger, Storage: corruptibleStore, MasterKeys: []string{masterKey}, BearerToken: bearerToken, @@ -167,7 +161,6 @@ func TestStorageCorruption_EmptyDEK(t *testing.T) { // TestStorageCorruption_PartialDEK verifies that truncated DEK data is handled. func TestStorageCorruption_PartialDEK(t *testing.T) { - logger := logging.NewNoop() store := newCorruptibleStorage(t) _, masterKey, err := keys.GenerateMasterKey() @@ -175,7 +168,6 @@ func TestStorageCorruption_PartialDEK(t *testing.T) { bearerToken := "test-token-" + uid.New("test") service, err := New(Config{ - Logger: logger, Storage: store, MasterKeys: []string{masterKey}, BearerToken: bearerToken, @@ -242,7 +234,6 @@ func TestStorageCorruption_PartialDEK(t *testing.T) { // because they don't change the actual encrypted key material. Only corruption // of the encrypted.ciphertext or encrypted.nonce will be detected by GCM. func TestStorageCorruption_BitFlipInDEK(t *testing.T) { - logger := logging.NewNoop() store := newCorruptibleStorage(t) _, masterKey, err := keys.GenerateMasterKey() @@ -250,7 +241,6 @@ func TestStorageCorruption_BitFlipInDEK(t *testing.T) { bearerToken := "test-token-" + uid.New("test") service, err := New(Config{ - Logger: logger, Storage: store, MasterKeys: []string{masterKey}, BearerToken: bearerToken, @@ -331,7 +321,6 @@ func TestStorageCorruption_BitFlipInDEK(t *testing.T) { // TestStorageCorruption_InvalidProtobufDEK verifies that invalid protobuf // data in place of a DEK is handled. func TestStorageCorruption_InvalidProtobufDEK(t *testing.T) { - logger := logging.NewNoop() store := newCorruptibleStorage(t) _, masterKey, err := keys.GenerateMasterKey() @@ -339,7 +328,6 @@ func TestStorageCorruption_InvalidProtobufDEK(t *testing.T) { bearerToken := "test-token-" + uid.New("test") service, err := New(Config{ - Logger: logger, Storage: store, MasterKeys: []string{masterKey}, BearerToken: bearerToken, diff --git a/svc/vault/run.go b/svc/vault/run.go index 7c0f0ad485..f363735a8c 100644 --- a/svc/vault/run.go +++ b/svc/vault/run.go @@ -3,13 +3,12 @@ package vault import ( "context" "fmt" - "log/slog" "net/http" "time" "github.com/unkeyed/unkey/gen/proto/vault/v1/vaultv1connect" + "github.com/unkeyed/unkey/pkg/logger" "github.com/unkeyed/unkey/pkg/otel" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/pkg/runner" "github.com/unkeyed/unkey/pkg/version" "github.com/unkeyed/unkey/svc/vault/internal/storage" @@ -23,6 +22,11 @@ func Run(ctx context.Context, cfg Config) error { return fmt.Errorf("bad config: %w", err) } + logger.SetSampler(logger.TailSampler{ + SlowThreshold: cfg.LogSlowThreshold, + SampleRate: cfg.LogSampleRate, + }) + var shutdownGrafana func(context.Context) error if cfg.OtelEnabled { shutdownGrafana, err = otel.InitGrafana(ctx, otel.Config{ @@ -37,12 +41,7 @@ func Run(ctx context.Context, cfg Config) error { } } - logger := logging.New() - if cfg.InstanceID != "" { - logger = logger.With(slog.String("instanceID", cfg.InstanceID)) - } - - r := runner.New(logger) + r := runner.New() defer r.Recover() r.DeferCtx(shutdownGrafana) @@ -56,7 +55,6 @@ func Run(ctx context.Context, cfg Config) error { S3Bucket: cfg.S3Bucket, S3AccessKeyID: cfg.S3AccessKeyID, S3AccessKeySecret: cfg.S3AccessKeySecret, - Logger: logger, }) if err != nil { return fmt.Errorf("failed to create s3 storage: %w", err) @@ -64,7 +62,6 @@ func Run(ctx context.Context, cfg Config) error { s3 = storagemiddleware.WithTracing("s3", s3) v, err := vault.New(vault.Config{ - Logger: logger, Storage: s3, MasterKeys: cfg.MasterKeys, BearerToken: cfg.BearerToken, diff --git a/svc/vault/testutil/BUILD.bazel b/svc/vault/testutil/BUILD.bazel index 6e6e2d5e47..0c8fd03e5e 100644 --- a/svc/vault/testutil/BUILD.bazel +++ b/svc/vault/testutil/BUILD.bazel @@ -8,7 +8,6 @@ go_library( deps = [ "//gen/proto/vault/v1/vaultv1connect", "//pkg/dockertest", - "//pkg/otel/logging", "//svc/vault/internal/keys", "//svc/vault/internal/storage", "//svc/vault/internal/vault", diff --git a/svc/vault/testutil/testutil.go b/svc/vault/testutil/testutil.go index f30cc15a74..772f4090eb 100644 --- a/svc/vault/testutil/testutil.go +++ b/svc/vault/testutil/testutil.go @@ -13,7 +13,6 @@ import ( "github.com/stretchr/testify/require" "github.com/unkeyed/unkey/gen/proto/vault/v1/vaultv1connect" "github.com/unkeyed/unkey/pkg/dockertest" - "github.com/unkeyed/unkey/pkg/otel/logging" "github.com/unkeyed/unkey/svc/vault/internal/keys" "github.com/unkeyed/unkey/svc/vault/internal/storage" "github.com/unkeyed/unkey/svc/vault/internal/vault" @@ -45,7 +44,6 @@ func StartTestVault(t *testing.T) *TestVault { S3Bucket: "vault-test", S3AccessKeyID: s3.AccessKeyID, S3AccessKeySecret: s3.SecretAccessKey, - Logger: logging.NewNoop(), }) require.NoError(t, err) @@ -58,7 +56,6 @@ func StartTestVault(t *testing.T) *TestVault { // Create vault service v, err := vault.New(vault.Config{ Storage: st, - Logger: logging.NewNoop(), MasterKeys: []string{masterKey}, BearerToken: token, }) @@ -90,9 +87,7 @@ func StartTestVaultWithMemory(t *testing.T) *TestVault { t.Helper() // Create in-memory storage - st, err := storage.NewMemory(storage.MemoryConfig{ - Logger: logging.NewNoop(), - }) + st, err := storage.NewMemory() require.NoError(t, err) // Generate master key @@ -104,7 +99,6 @@ func StartTestVaultWithMemory(t *testing.T) *TestVault { // Create vault service v, err := vault.New(vault.Config{ Storage: st, - Logger: logging.NewNoop(), MasterKeys: []string{masterKey}, BearerToken: token, })