Skip to content

Commit

Permalink
feat(loggerx): add Fatal level with configurable exit behavior
Browse files Browse the repository at this point in the history
- Introduced `LoggerOptions: DisableFatalExit` to toggle exiting on Fatal logs.
- Ensured backward compatibility by defaulting to exiting on Fatal logs.
  • Loading branch information
surajmn1 committed Nov 29, 2024
1 parent 0bc5ea0 commit cef9686
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion loggerx/logrus.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,27 @@ import (
var logrusLogger *logrus.Logger
var req *http.Request

func Init() func(next http.Handler) http.Handler {
type LoggerOptions struct {
DisableFatalExit bool
}

func Init(opts ...*LoggerOptions) func(next http.Handler) http.Handler {
logrusLogger = logrus.New()
logrusLogger.Formatter = &logrus.TextFormatter{
ForceColors: true,
FullTimestamp: true,
DisableLevelTruncation: true,
}

// Apply options if provided
if len(opts) > 0 && opts[0] != nil {
if opts[0].DisableFatalExit {
logrusLogger.ExitFunc = func(code int) {
// No-op: Do nothing on Fatal logs
}
}
}

return NewStructuredLogger(logrusLogger)
}

Expand Down Expand Up @@ -61,6 +75,18 @@ func (l *StructuredLoggerEntry) Write(status, bytes int, header http.Header, ela
l.Logger.Infoln("request complete")
}

func Fatal(fatal string) {
logrusFields := logrus.Fields{}
pc, file, line, ok := runtime.Caller(1)
if ok {
funcName := runtime.FuncForPC(pc).Name()
pwd, _ := os.Getwd()
relPath := file[len(pwd):]
logrusFields["source"] = fmt.Sprintf("%s:%s:%v", relPath, path.Base(funcName), line)
}
logrusLogger.WithFields(logrusFields).Fatal(fatal)
}

func Error(err error) {
logFields := GetDefaultFields()

Expand Down

0 comments on commit cef9686

Please sign in to comment.