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
71 changes: 69 additions & 2 deletions slogger/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# slogger

A `log/slog` logger with a configurable format, a hot-reloadable log level and a
custom writer.
A `log/slog` logger with a configurable format, a hot-reloadable log level, a
custom writer, an optional source code position and an optional rewriting of the
attributes.

The module is split into two packages:

Expand Down Expand Up @@ -30,8 +31,14 @@ type Options struct {
// Writer is an optional writer the logs are written to.
// If it is not set, the logs are written to os.Stdout.
Writer io.Writer
// ReplaceAttr rewrites each non-group attribute before it is written.
// It is called with the groups the attribute belongs to. If it returns a
// zero slog.Attr, the attribute is dropped.
ReplaceAttr func(groups []string, a slog.Attr) slog.Attr
// Format is the log output format. Allowed values: "json" and "text".
Format string
// AddSource adds the source code position of the log record to it.
AddSource bool
}

func New(ctx context.Context, opts Options) (*slog.Logger, error)
Expand All @@ -44,6 +51,10 @@ func NewToContext(ctx context.Context, opts Options) (context.Context, error)
- `LevelReloadCond` — the condition variable that notifies the logger about a level
change. Without it the level is set once, at startup.
- `Writer` — the destination of the records; `os.Stdout` by default.
- `AddSource` — adds the source code position of the record to it; see
[Source code position](#source-code-position).
- `ReplaceAttr` — rewrites the attributes before they are written; see
[Attribute rewriting](#attribute-rewriting).

`NewToContext` is the same as `New`, but it puts the logger into the returned
context, so it can be used with the [`ctxlog`](#context-logger) helpers. The
Expand Down Expand Up @@ -83,6 +94,62 @@ logger, err := slogger.New(ctx, slogger.Options{
The level is applied by the handler through a `slog.LevelVar`: the records below it
are dropped before they are formatted.

## Source code position

With `AddSource` the source code position of the record is added to it:

```go
logger, err := slogger.New(ctx, slogger.Options{
Leveler: func() string { return "INFO" },
Format: "json",
AddSource: true,
})

logger.Info("Server started")
// {"time":"...","level":"INFO","msg":"Server started","source":{"function":"main.main","file":"main.go","line":17}}
```

Without it the record has no `source` attribute.

## Attribute rewriting

`ReplaceAttr` is called for every non-group attribute of the record before it
is written. It can change the attribute, or drop it by returning a zero
`slog.Attr`:

```go
logger, err := slogger.New(ctx, slogger.Options{
Leveler: func() string { return "INFO" },
Format: "json",
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == "password" {
return slog.String(a.Key, "***")
}

return a
},
})

logger.Info("User logged in", slog.String("user_id", "42"), slog.String("password", "secret"))
// {"time":"...","level":"INFO","msg":"User logged in","user_id":"42","password":"***"}
```

The built-in attributes (`time`, `level`, `msg` and, with `AddSource`,
`source`) are passed to `ReplaceAttr` as well.

The first argument of `ReplaceAttr` contains the groups the attribute belongs
to, so the attributes of a group can be handled separately:

```go
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if len(groups) == 1 && groups[0] == "http" && a.Key == "user_agent" {
return slog.String(a.Key, "***")
}

return a
},
```

## Log level reload

With a `*sync.Cond` in `LevelReloadCond` the logger re-reads the level on every
Expand Down
23 changes: 15 additions & 8 deletions slogger/slogger.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,14 @@ type Options struct {
// Writer is an optional writer the logs are written to.
// If it is not set, the logs are written to [os.Stdout].
Writer io.Writer
// ReplaceAttr rewrites each non-group attribute before it is written.
// It is called with the groups the attribute belongs to. If it returns a
// zero [slog.Attr], the attribute is dropped.
ReplaceAttr func(groups []string, a slog.Attr) slog.Attr
// Format is the log output format. Allowed values: "json" and "text".
Format string
// AddSource adds the source code position of the log record to it.
AddSource bool
}

// New initializes and returns a [slog.Logger] or an error.
Expand All @@ -36,24 +42,25 @@ func New(ctx context.Context, opts Options) (*slog.Logger, error) {
return nil, err
}

var (
handler slog.Handler
options = &slog.HandlerOptions{Level: level}
)

var writer io.Writer = os.Stdout
if opts.Writer != nil {
writer = opts.Writer
}

logFormat := opts.Format
switch logFormat {
options := &slog.HandlerOptions{
AddSource: opts.AddSource,
Level: level,
ReplaceAttr: opts.ReplaceAttr,
}

var handler slog.Handler
switch opts.Format {
case "json":
handler = slog.NewJSONHandler(writer, options)
case "text":
handler = slog.NewTextHandler(writer, options)
default:
return nil, fmt.Errorf("unknown log format %q", logFormat)
return nil, fmt.Errorf("unknown log format %q", opts.Format)
}

l := slog.New(handler)
Expand Down
156 changes: 156 additions & 0 deletions slogger/slogger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,162 @@ func TestNew_CustomWriter(t *testing.T) {
assert.Contains(t, buf.String(), "Custom writer")
}

func TestNew_AddSource(t *testing.T) {
t.Parallel()

t.Run("adds the source code position", func(t *testing.T) {
t.Parallel()

buf := &safeBuffer{}
logger, err := New(t.Context(), Options{
Leveler: func() string { return "INFO" },
Format: "json",
Writer: buf,
AddSource: true,
})
require.NoError(t, err)

logger.Info("Hello")

record := map[string]any{}
require.NoError(t, json.Unmarshal([]byte(buf.String()), &record))

source, ok := record["source"].(map[string]any)
require.True(t, ok)
assert.Contains(t, source["file"], "slogger_test.go")
assert.Contains(t, source["function"], "TestNew_AddSource")
assert.Positive(t, source["line"])
})

t.Run("omits the source code position by default", func(t *testing.T) {
t.Parallel()

buf := &safeBuffer{}
logger, err := New(t.Context(), Options{
Leveler: func() string { return "INFO" },
Format: "json",
Writer: buf,
})
require.NoError(t, err)

logger.Info("Hello")

record := map[string]any{}
require.NoError(t, json.Unmarshal([]byte(buf.String()), &record))

assert.NotContains(t, record, "source")
})
}

func TestNew_ReplaceAttr(t *testing.T) {
t.Parallel()

t.Run("rewrites the attribute", func(t *testing.T) {
t.Parallel()

buf := &safeBuffer{}
logger, err := New(t.Context(), Options{
Leveler: func() string { return "INFO" },
Format: "json",
Writer: buf,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == "password" {
return slog.String(a.Key, "***")
}

return a
},
})
require.NoError(t, err)

logger.Info("Hello", slog.String("user_id", "42"), slog.String("password", "secret"))

record := map[string]any{}
require.NoError(t, json.Unmarshal([]byte(buf.String()), &record))
assert.Equal(t, "42", record["user_id"])
assert.Equal(t, "***", record["password"])
})

t.Run("drops the attribute", func(t *testing.T) {
t.Parallel()

buf := &safeBuffer{}
logger, err := New(t.Context(), Options{
Leveler: func() string { return "INFO" },
Format: "json",
Writer: buf,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == "password" {
return slog.Attr{}
}

return a
},
})
require.NoError(t, err)

logger.Info("Hello", slog.String("user_id", "42"), slog.String("password", "secret"))

record := map[string]any{}
require.NoError(t, json.Unmarshal([]byte(buf.String()), &record))
assert.Equal(t, "42", record["user_id"])
assert.NotContains(t, record, "password")
})

t.Run("rewrites the built-in attributes", func(t *testing.T) {
t.Parallel()

buf := &safeBuffer{}
logger, err := New(t.Context(), Options{
Leveler: func() string { return "INFO" },
Format: "json",
Writer: buf,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.MessageKey {
return slog.String(slog.MessageKey, "***")
}

return a
},
})
require.NoError(t, err)

logger.Info("Hello")

record := map[string]any{}
require.NoError(t, json.Unmarshal([]byte(buf.String()), &record))
assert.Equal(t, "***", record[slog.MessageKey])
})

t.Run("receives the groups of the attribute", func(t *testing.T) {
t.Parallel()

buf := &safeBuffer{}
logger, err := New(t.Context(), Options{
Leveler: func() string { return "INFO" },
Format: "json",
Writer: buf,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if len(groups) == 1 && groups[0] == "http" && a.Key == "user_agent" {
return slog.String(a.Key, "***")
}

return a
},
})
require.NoError(t, err)

logger.WithGroup("http").Info("Hello", slog.String("user_agent", "curl"))

record := map[string]any{}
require.NoError(t, json.Unmarshal([]byte(buf.String()), &record))

group, ok := record["http"].(map[string]any)
require.True(t, ok)
assert.Equal(t, "***", group["user_agent"])
})
}

func TestNew_LevelReload(t *testing.T) {
t.Run("lowers the level", func(t *testing.T) {
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
Expand Down
Loading