In Go's slog HandlerOptions, the AddSource
option can show the /full/path/filename:line
. It's too long!
What's the simplest way to let it only show filename:line
, or relative-path-to-project/filename:line
like zap logger? Thanks
type HandlerOptions struct {
// AddSource causes the handler to compute the source code position
// of the log statement and add a SourceKey attribute to the output.
AddSource bool
You can add to options user-defined filter for attributes and in case of source use filepath.Base
to cut the path. You shoud also add import "path/filepath"
to use it.
type HandlerOptions struct {
AddSource bool,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.SourceKey {
a.Value := filepath.Base(a.Value)
}
return a
}
}
https://pkg.go.dev/log/slog#HandlerOptions (see example below)