From 549e53b9455deeeb35f998c36ca65bf2a58d76bd Mon Sep 17 00:00:00 2001 From: Starttoaster Date: Thu, 20 Jun 2024 18:34:36 -0700 Subject: [PATCH] Add Fatal wrapper function to slogs --- pkg/slogs/README.md | 4 ++-- pkg/slogs/slogs.go | 19 ++++++++++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/pkg/slogs/README.md b/pkg/slogs/README.md index 0fdb5c4..627c992 100644 --- a/pkg/slogs/README.md +++ b/pkg/slogs/README.md @@ -17,10 +17,10 @@ func main() { slogs.Init("info") // Logs a hello world message at the info level - slogs.Logger.Info("hello world") + slogs.Logr.Info("hello world") // Logs an error message at the error level - slogs.Logger.Error("we received an error") + slogs.Logr.Error("we received an error") } ``` diff --git a/pkg/slogs/slogs.go b/pkg/slogs/slogs.go index ad0cb16..91a2f16 100644 --- a/pkg/slogs/slogs.go +++ b/pkg/slogs/slogs.go @@ -7,12 +7,17 @@ import ( "strings" ) -// Logger is a custom text logger from the stdlib slog package -var Logger *slog.Logger +// Logr is a custom text logger from the stdlib slog package +var Logr Logger + +// Logger is a wrapper around the slog logger struct so we can have a type that is owned by this scope to create additional wrapper functions around +type Logger struct { + *slog.Logger +} // Init custom init function that accepts the log level for the application and initializes a stdout slog logger func Init(level string) { - Logger = slog.New( + l := slog.New( slog.NewTextHandler( os.Stdout, &slog.HandlerOptions{ @@ -20,6 +25,7 @@ func Init(level string) { }, ), ) + Logr = Logger{l} } // Function to convert log level string to slog.Level @@ -38,3 +44,10 @@ func parseLogLevel(level string) slog.Level { return slog.LevelInfo } } + +// Fatal is a wrapper around the standard slog Error function that exits 1 after it is called. +// Similar to the stdlib log.Fatal function +func (l Logger) Fatal(msg string, args ...any) { + l.Error(msg, args...) + os.Exit(1) +}