Skip to content

proposal: log/slog: builtin support for helper functions #59145

Closed
@pohly

Description

@pohly

When calling a Logger method inside a helper function, the recorded source code is the source code of the helper:


func Foo() {
   logSomething("hello world", "key": 1, "value": "xyz")
}

func logSomething(msg string, kvs ...any) {
   slog.Default().Info("logging " + msg", kvs...)
}

Other logging libraries (zap, go-logr) have a WithCallDepth call for this. testing.T has Helper, but that is less flexible.

It would be useful to add Logger.WithCallDepth, then this example would become:

func logSomething(msg string, kvs ...any) {
   slog.Default().WithCallDepth(1).Info("logging " + msg", kvs...)
}

The only solution right now is for logSomething to translate its arguments into a Record, do stack unwinding, then call Handler.Handle. This is doable, but implies copying quite a bit of code from slog because the helper functions which do that in Logger are not exported (and probably shouldn't be).

cc @jba

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions