From cf02659ac885052d06e33878d806b365fb5567af Mon Sep 17 00:00:00 2001 From: Pat Downey Date: Sat, 14 Nov 2026 20:31:51 +0000 Subject: [PATCH] feat: add ServiceLogger, and set the zerolog default context logger once ServiceLogger returns a context whose logger carries service=name, without touching any zerolog global, so several services in one process can name themselves without racing to write DefaultContextLogger. The process-level setting moves to logging.ConfigureProcessLogging, which does what ConfigureCmdLogger does and then makes the logger the default context logger, so zerolog.Ctx works on a shutdown context made from context.Background(). InitConfig calls it in place of ConfigureCmdLogger. Fixes #20 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01SS4MAwAn85D1gkEzLtjYaZ --- config.go | 4 +- logging/logging.go | 23 ++++++++++ logging/logging_test.go | 16 +++++++ servicelogger.go | 25 +++++++++++ servicelogger_test.go | 94 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 160 insertions(+), 2 deletions(-) create mode 100644 servicelogger.go create mode 100644 servicelogger_test.go diff --git a/config.go b/config.go index 06d751c..fa993cb 100644 --- a/config.go +++ b/config.go @@ -119,7 +119,7 @@ func defaultInitConfigOptions() initConfigOptions { // WithoutLogging disables automatic logging configuration during InitConfig. // -// By default, InitConfig configures the global logger via ConfigureCmdLogger. +// By default, InitConfig configures the global logger via ConfigureProcessLogging. // Use this option in tests or when managing logging independently. func WithoutLogging() InitConfigOption { return func(o *initConfigOptions) { @@ -186,7 +186,7 @@ func InitConfig(orgName, appName string, cmd *cobra.Command, cfg any, opts ...In } if options.configureLogging { - logging.ConfigureCmdLogger(c.Logging) + logging.ConfigureProcessLogging(c.Logging) } err = UnmarshalConfig(v, cfg) diff --git a/logging/logging.go b/logging/logging.go index 204a3bf..f10d843 100644 --- a/logging/logging.go +++ b/logging/logging.go @@ -6,6 +6,7 @@ import ( defaultLog "log" "os" "path/filepath" + "sync" "time" "github.com/mitchellh/go-homedir" @@ -41,6 +42,28 @@ func WithDefaultLogLevel(level zerolog.Level) func(*Config) { } } +// processLoggingMu serialises ConfigureProcessLogging's write of the zerolog +// global it owns. +var processLoggingMu sync.Mutex + +// ConfigureProcessLogging sets up logging for the whole process: it does what +// ConfigureCmdLogger does, then makes the resulting logger zerolog's +// DefaultContextLogger, so zerolog.Ctx works on a context that carries no +// logger, such as a shutdown context made from context.Background(). +// +// It changes process-wide state, so call it once, from the command's entry +// point. A service names itself per context with cli.ServiceLogger, which +// leaves these globals alone, so several services in one process do not race +// to write them. +func ConfigureProcessLogging(c Config, opts ...Option) { + processLoggingMu.Lock() + defer processLoggingMu.Unlock() + + ConfigureCmdLogger(c, opts...) + logger := log.Logger + zerolog.DefaultContextLogger = &logger +} + // ConfigureCmdLogger configures the global zerolog logger with the provided settings and options. // // It applies all options, then sets up log level and output configuration. diff --git a/logging/logging_test.go b/logging/logging_test.go index 20070b0..fa380ed 100644 --- a/logging/logging_test.go +++ b/logging/logging_test.go @@ -2,12 +2,14 @@ package logging_test import ( "bytes" + "context" "errors" "os" "os/exec" "testing" "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -233,3 +235,17 @@ func BenchmarkConfigureCmdLogger(b *testing.B) { logging.ConfigureCmdLogger(cfg) } } + +func TestConfigureProcessLogging_MakesTheLoggerTheContextDefault(t *testing.T) { + previous := zerolog.DefaultContextLogger + previousLogger := log.Logger + t.Cleanup(func() { + zerolog.DefaultContextLogger = previous + log.Logger = previousLogger + }) + + logging.ConfigureProcessLogging(logging.Config{}) + + require.NotNil(t, zerolog.DefaultContextLogger) + assert.NotEqual(t, zerolog.Disabled, zerolog.Ctx(context.Background()).GetLevel(), "a context with no logger now gets the process logger") +} diff --git a/servicelogger.go b/servicelogger.go new file mode 100644 index 0000000..7ed7383 --- /dev/null +++ b/servicelogger.go @@ -0,0 +1,25 @@ +package cli + +import ( + "context" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" +) + +// ServiceLogger returns a context whose logger carries service=name. It enriches +// the logger already in ctx, or the process logger if ctx has none, and it does +// not touch any zerolog global, so several services in one process can each +// name themselves without racing over shared state. +// +// A shutdown path should derive its context with context.WithoutCancel(ctx), +// not context.Background(), so it keeps the service label. +func ServiceLogger(ctx context.Context, name string) context.Context { + base := *zerolog.Ctx(ctx) + if base.GetLevel() == zerolog.Disabled { + // ctx carries no logger and no default is set. + base = log.Logger + } + + return base.With().Str("service", name).Logger().WithContext(ctx) +} diff --git a/servicelogger_test.go b/servicelogger_test.go new file mode 100644 index 0000000..9344273 --- /dev/null +++ b/servicelogger_test.go @@ -0,0 +1,94 @@ +package cli_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "testing" + + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dioad/cli" +) + +func logLine(t *testing.T, buf *bytes.Buffer) map[string]any { + t.Helper() + var line map[string]any + require.NoError(t, json.Unmarshal(buf.Bytes(), &line), "log output: %s", buf.String()) + + return line +} + +func TestServiceLogger_AddsTheServiceField(t *testing.T) { + t.Parallel() + var buf bytes.Buffer + ctx := zerolog.New(&buf).With().Str("request", "r1").Logger().WithContext(context.Background()) + + zerolog.Ctx(cli.ServiceLogger(ctx, "accounting")).Error().Msg("hello") + + line := logLine(t, &buf) + assert.Equal(t, "accounting", line["service"]) + assert.Equal(t, "r1", line["request"], "fields already on the logger are kept") +} + +func TestServiceLogger_DoesNotChangeTheCallersContext(t *testing.T) { + t.Parallel() + var buf bytes.Buffer + ctx := zerolog.New(&buf).WithContext(context.Background()) + + _ = cli.ServiceLogger(ctx, "accounting") + zerolog.Ctx(ctx).Error().Msg("hello") + + assert.NotContains(t, logLine(t, &buf), "service") +} + +func TestServiceLogger_LeavesZerologGlobalsAlone(t *testing.T) { + before, level, format := zerolog.DefaultContextLogger, zerolog.GlobalLevel(), zerolog.TimeFieldFormat + + _ = cli.ServiceLogger(zerolog.New(&bytes.Buffer{}).WithContext(context.Background()), "accounting") + + assert.Same(t, before, zerolog.DefaultContextLogger) + assert.Equal(t, level, zerolog.GlobalLevel()) + assert.Equal(t, format, zerolog.TimeFieldFormat) +} + +func TestServiceLogger_CanBeCalledConcurrentlyForSeveralServices(t *testing.T) { + t.Parallel() + var bufs [4]bytes.Buffer + done := make(chan struct{}) + for i := range bufs { + go func() { + defer func() { done <- struct{}{} }() + ctx := zerolog.New(&bufs[i]).WithContext(context.Background()) + ctx = cli.ServiceLogger(ctx, fmt.Sprintf("svc-%d", i)) + zerolog.Ctx(ctx).Error().Msg("up") + }() + } + for range bufs { + <-done + } + + for i := range bufs { + assert.Equal(t, fmt.Sprintf("svc-%d", i), logLine(t, &bufs[i])["service"], "each service keeps its own label") + } +} + +func ExampleServiceLogger() { + var out bytes.Buffer + ctx := zerolog.New(&out).WithContext(context.Background()) + + before := zerolog.DefaultContextLogger + ctx = cli.ServiceLogger(ctx, "accounting") + // Error level, so the line is written whatever global level other code + // in the process has set. + zerolog.Ctx(ctx).Error().Msg("failed to start") + + fmt.Print(out.String()) + fmt.Println("globals untouched:", zerolog.DefaultContextLogger == before) + // Output: + // {"level":"error","service":"accounting","message":"failed to start"} + // globals untouched: true +}