Skip to content

Commit

Permalink
feat: Add support for emitting formatted log through panic when invok…
Browse files Browse the repository at this point in the history
…ing log.Fatal(...) or log.FatalF(...).
  • Loading branch information
tuxgal committed Sep 25, 2024
1 parent 3b5da7b commit 4c0ef54
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
18 changes: 16 additions & 2 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ type configInternal struct {
skipLogLevel bool
// skipCallerInfo set to true skips logging the call site information.
skipCallerInfo bool
// panicInFatal set to true causes the log message to be emitted
// through panic() after logging, instead of the default behavior of
// exiting with a status code 1 when using Fatal or FatalF logging methods.
panicInFatal bool
// timestampLoggingFormat determines the format for logging the timestamps.
timestampLoggingFormat string
}
Expand All @@ -50,13 +54,23 @@ func newLoggerForConfig(config *configInternal) zzzlogi.Logger {
func (l *loggerImpl) Fatal(args ...interface{}) {
l.log(LvlFatal, 1, defaultFormat(len(args)), args...)
l.write("\n%s\n", stackTraces())
os.Exit(1)

if l.config.panicInFatal {
panic(fmt.Sprintf(defaultFormat(len(args)), args...))
} else {
os.Exit(1)
}
}

func (l *loggerImpl) Fatalf(format string, args ...interface{}) {
l.log(LvlFatal, 1, format, args...)
l.write("\n%s\n", stackTraces())
os.Exit(1)

if l.config.panicInFatal {
panic(fmt.Sprintf(format, args...))
} else {
os.Exit(1)
}
}

func (l *loggerImpl) Error(args ...interface{}) {
Expand Down
5 changes: 5 additions & 0 deletions zzzlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ type Config struct {
SkipLogLevel bool
// SkipCallerInfo set to true skips logging the call site information.
SkipCallerInfo bool
// PanicInFatal set to true causes the log message to be emitted
// through panic() after logging, instead of the default behavior of
// exiting with a status code 1 when using Fatal or FatalF logging methods.
PanicInFatal bool
// TimestampLoggingFormat determines the format for logging the timestamps.
TimestampLoggingFormat string
}
Expand All @@ -56,6 +60,7 @@ func NewLogger(userConfig *Config) zzzlogi.Logger {
c.skipTimestamp = userConfig.SkipTimestamp
c.skipLogLevel = userConfig.SkipLogLevel
c.skipCallerInfo = userConfig.SkipCallerInfo
c.panicInFatal = userConfig.PanicInFatal
if userConfig.TimestampLoggingFormat != "" {
c.timestampLoggingFormat = userConfig.TimestampLoggingFormat
} else {
Expand Down

0 comments on commit 4c0ef54

Please sign in to comment.