From 15b1dffa32e1fe5bebfd2cb2a824baafefe1ccf9 Mon Sep 17 00:00:00 2001 From: dave Date: Wed, 6 Mar 2024 21:04:18 -0700 Subject: [PATCH] add fatalhandler to logger, called to handle a fatal log message --- pkg/etcdmtr/log.go | 38 ++++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/pkg/etcdmtr/log.go b/pkg/etcdmtr/log.go index a371dcb..08dbeab 100644 --- a/pkg/etcdmtr/log.go +++ b/pkg/etcdmtr/log.go @@ -87,11 +87,12 @@ func (f *LogFormat) AppendTimestamp(format string) *LogFormat { } type ELog struct { - parent *ELog - name string - Level LogLevel - Format *LogFormat - Output io.Writer + parent *ELog + name string + Level LogLevel + Format *LogFormat + Output io.Writer + FatalHandler func(*ELog, int, string, ...any) } func NewRootLogger() *ELog { @@ -110,11 +111,17 @@ func NewRootLogger() *ELog { ) } +func FatalHandler(logger *ELog, exitCode int, message string, a ...any) { + _, _ = logger.Log(LOGLEVEL_FATAL, message, a) + os.Exit(exitCode) +} + func NewRootLoggerWithFormat(format *LogFormat) *ELog { return &ELog{ - name: "main", - Format: format, - Output: os.Stderr, + name: "main", + Format: format, + Output: os.Stderr, + FatalHandler: FatalHandler, } } @@ -126,7 +133,7 @@ func (e *ELog) GetLogger(name string) *ELog { } } -func (e *ELog) _Log(level LogLevel, message string, a ...any) (n int, err error) { +func (e *ELog) Log(level LogLevel, message string, a ...any) (n int, err error) { return e._DoLog(level, nil, message, a...) } @@ -169,23 +176,23 @@ func (e *ELog) _DoLog(level LogLevel, path []string, message string, a ...any) ( } func (e *ELog) Debug(message string, a ...any) (n int, err error) { - return e._Log(LOGLEVEL_DEBUG, message, a...) + return e.Log(LOGLEVEL_DEBUG, message, a...) } func (e *ELog) Info(message string, a ...any) (n int, err error) { - return e._Log(LOGLEVEL_INFO, message, a...) + return e.Log(LOGLEVEL_INFO, message, a...) } func (e *ELog) Warning(message string, a ...any) (n int, err error) { - return e._Log(LOGLEVEL_WARNING, message, a...) + return e.Log(LOGLEVEL_WARNING, message, a...) } func (e *ELog) Error(message string, a ...any) (n int, err error) { - return e._Log(LOGLEVEL_ERROR, message, a...) + return e.Log(LOGLEVEL_ERROR, message, a...) } func (e *ELog) Critical(message string, a ...any) (n int, err error) { - return e._Log(LOGLEVEL_CRITICAL, message, a...) + return e.Log(LOGLEVEL_CRITICAL, message, a...) } func (e *ELog) Fatal(message string, a ...any) (n int, err error) { @@ -193,8 +200,7 @@ func (e *ELog) Fatal(message string, a ...any) (n int, err error) { } func (e *ELog) Fatalc(exitCode int, message string, a ...any) (n int, err error) { - _, _ = e._Log(LOGLEVEL_FATAL, message, a...) - os.Exit(exitCode) + e.FatalHandler(e, exitCode, message, a...) return 0, nil }