Last active
April 1, 2024 15:44
-
-
Save HalCanary/6bd335057c65f3b803088cc55b9ebd2b to your computer and use it in GitHub Desktop.
log/slog Lshortfile replacement example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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