Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
Expand Down
23 changes: 23 additions & 0 deletions logging/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
defaultLog "log"
"os"
"path/filepath"
"sync"
"time"

"github.com/mitchellh/go-homedir"
Expand Down Expand Up @@ -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.
Expand Down
16 changes: 16 additions & 0 deletions logging/logging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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")
}
25 changes: 25 additions & 0 deletions servicelogger.go
Original file line number Diff line number Diff line change
@@ -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)
}
94 changes: 94 additions & 0 deletions servicelogger_test.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading