diff --git a/log/custom_log_hooks.go b/log/custom_log_hooks.go new file mode 100644 index 00000000..fad6e829 --- /dev/null +++ b/log/custom_log_hooks.go @@ -0,0 +1,17 @@ +package log + +// CustomLogHook is a function type for external log handling. It should return +// true if the library's internal logging system should be bypassed, or false +// if the library's internal logging system should be used. +type CustomLogHook func(header, subLoggerName string, a ...any) (bypassLibraryLogSystem bool) + +var customLogHook CustomLogHook + +// SetCustomLogHook sets a custom log hook function that allows the complete +// bypass of the library's internal logging system. This is useful for +// implementing custom log handling. +func SetCustomLogHook(h CustomLogHook) { + mu.Lock() + customLogHook = h + mu.Unlock() +} diff --git a/log/custom_log_hooks_test.go b/log/custom_log_hooks_test.go new file mode 100644 index 00000000..7e778856 --- /dev/null +++ b/log/custom_log_hooks_test.go @@ -0,0 +1,11 @@ +package log + +import "testing" + +func TestSetCustomLoghook(t *testing.T) { + t.Parallel() + logHook := func(_ string, _ string, _ ...interface{}) (bypassLibraryLogSystem bool) { + return false + } + SetCustomLogHook(logHook) +} diff --git a/log/loggers.go b/log/loggers.go index 8db35e21..e7731b39 100644 --- a/log/loggers.go +++ b/log/loggers.go @@ -264,12 +264,22 @@ func (l *fields) stage(header string, deferFunc deferral) { logFieldsPool.Put(l) } -// stageln stages a log event -func (l *fields) stageln(header string, a ...interface{}) { +// stageln logs a message with the given header and arguments. It uses the +// custom log hook if set, otherwise falls back to the library's internal log +// system. +func (l *fields) stageln(header string, a ...any) { + if customLogHook != nil && customLogHook(header, l.name, a...) { + return + } l.stage(header, func() string { return fmt.Sprint(a...) }) } -// stagef stages a log event -func (l *fields) stagef(header, format string, a ...interface{}) { +// stagef logs a formatted message with the given header and arguments. It uses +// the custom log hook if set, otherwise falls back to the library's internal +// log system. +func (l *fields) stagef(header, format string, a ...any) { + if customLogHook != nil && customLogHook(header, l.name, fmt.Sprintf(format, a...)) { + return + } l.stage(header, func() string { return fmt.Sprintf(format, a...) }) }