Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Fatal wrapper function to slogs #36

Merged
merged 1 commit into from
Jun 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions pkg/slogs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
```

Expand Down
19 changes: 16 additions & 3 deletions pkg/slogs/slogs.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,25 @@ 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{
Level: parseLogLevel(level),
},
),
)
Logr = Logger{l}
}

// Function to convert log level string to slog.Level
Expand All @@ -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)
}