Skip to content

Instantly share code, notes, and snippets.

@HalCanary
Last active April 1, 2024 15:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HalCanary/6bd335057c65f3b803088cc55b9ebd2b to your computer and use it in GitHub Desktop.
Save HalCanary/6bd335057c65f3b803088cc55b9ebd2b to your computer and use it in GitHub Desktop.
log/slog Lshortfile replacement example.
package main
import (
"os"
)
import (
"io"
"log/slog"
"path/filepath"
)
func makeLog(w io.Writer, level slog.Level) *slog.Logger {
return slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{
AddSource: true,
Level: &level,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.SourceKey {
source, _ := a.Value.Any().(*slog.Source)
if source != nil {
source.File = filepath.Base(source.File)
}
}
return a
},
}))
}
func main() {
logger := makeLog(os.Stderr, slog.LevelInfo)
logger.Info("Hello World!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment