From 13bbb7e51780b2f5143527219efb62a472bcc62e Mon Sep 17 00:00:00 2001 From: astraw99 Date: Fri, 19 Nov 2021 10:32:11 +0800 Subject: [PATCH] fix logger unlock on panic --- klog.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/klog.go b/klog.go index 45efbb075..ec0897687 100644 --- a/klog.go +++ b/klog.go @@ -918,6 +918,13 @@ func LogToStderr(stderr bool) { // output writes the data to the log files and releases the buffer. func (l *loggingT) output(s severity, log *logr.Logger, buf *buffer, depth int, file string, line int, alsoToStderr bool) { l.mu.Lock() + defer func() { + if err := recover(); err != nil { + l.mu.Unlock() // Make sure to do `Unlock` if panic occurs below (eg: #L938 Error) + os.Stderr.Write([]byte("panic observed in loggingT.output")) // Make sure the message appears somewhere. + } + }() + if l.traceLocation.isSet() { if l.traceLocation.match(file, line) { buf.Write(stacks(false)) @@ -928,7 +935,7 @@ func (l *loggingT) output(s severity, log *logr.Logger, buf *buffer, depth int, // TODO: set 'severity' and caller information as structured log info // keysAndValues := []interface{}{"severity", severityName[s], "file", file, "line", line} if s == errorLog { - l.logr.WithCallDepth(depth+3).Error(nil, string(data)) + l.logr.WithCallDepth(depth+3).Error(nil, string(data)) // If panic here will be captured by defer } else { log.WithCallDepth(depth + 3).Info(string(data)) } @@ -945,6 +952,7 @@ func (l *loggingT) output(s severity, log *logr.Logger, buf *buffer, depth int, if l.file[infoLog] == nil { if err := l.createFiles(infoLog); err != nil { os.Stderr.Write(data) // Make sure the message appears somewhere. + l.mu.Unlock() // At this point `logExitFunc` is nil (checked in #L1068), so `Unlock` needed. l.exit(err) } } @@ -953,6 +961,7 @@ func (l *loggingT) output(s severity, log *logr.Logger, buf *buffer, depth int, if l.file[s] == nil { if err := l.createFiles(s); err != nil { os.Stderr.Write(data) // Make sure the message appears somewhere. + l.mu.Unlock() // At this point `logExitFunc` is nil (checked in #L1068), so `Unlock` needed. l.exit(err) } }