Skip to content

Commit

Permalink
Merge pull request #36 from Chia-Network/fatallog
Browse files Browse the repository at this point in the history
Add Fatal wrapper function to slogs
  • Loading branch information
Starttoaster committed Jun 21, 2024
2 parents 456240d + 549e53b commit 1eae281
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
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)
}

0 comments on commit 1eae281

Please sign in to comment.