Skip to content

Commit aa7becc

Browse files
author
successwang
committed
fix logger unlock on panic
1 parent 9ad2462 commit aa7becc

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

‎klog.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -918,6 +918,13 @@ func LogToStderr(stderr bool) {
918918
// output writes the data to the log files and releases the buffer.
919919
func (l *loggingT) output(s severity, log *logr.Logger, buf *buffer, depth int, file string, line int, alsoToStderr bool) {
920920
l.mu.Lock()
921+
defer func() {
922+
if err := recover(); err != nil {
923+
l.mu.Unlock() // Make sure to do `Unlock` if panic occurs below (eg: #L938 Error)
924+
os.Stderr.Write([]byte("panic observed in loggingT.output")) // Make sure the message appears somewhere.
925+
}
926+
}()
927+
921928
if l.traceLocation.isSet() {
922929
if l.traceLocation.match(file, line) {
923930
buf.Write(stacks(false))
@@ -928,7 +935,7 @@ func (l *loggingT) output(s severity, log *logr.Logger, buf *buffer, depth int,
928935
// TODO: set 'severity' and caller information as structured log info
929936
// keysAndValues := []interface{}{"severity", severityName[s], "file", file, "line", line}
930937
if s == errorLog {
931-
l.logr.WithCallDepth(depth+3).Error(nil, string(data))
938+
l.logr.WithCallDepth(depth+3).Error(nil, string(data)) // If panic here will be captured by defer
932939
} else {
933940
log.WithCallDepth(depth + 3).Info(string(data))
934941
}
@@ -945,6 +952,7 @@ func (l *loggingT) output(s severity, log *logr.Logger, buf *buffer, depth int,
945952
if l.file[infoLog] == nil {
946953
if err := l.createFiles(infoLog); err != nil {
947954
os.Stderr.Write(data) // Make sure the message appears somewhere.
955+
l.mu.Unlock() // At this point `logExitFunc` is nil (checked in #L1068), so `Unlock` needed.
948956
l.exit(err)
949957
}
950958
}
@@ -953,6 +961,7 @@ func (l *loggingT) output(s severity, log *logr.Logger, buf *buffer, depth int,
953961
if l.file[s] == nil {
954962
if err := l.createFiles(s); err != nil {
955963
os.Stderr.Write(data) // Make sure the message appears somewhere.
964+
l.mu.Unlock() // At this point `logExitFunc` is nil (checked in #L1068), so `Unlock` needed.
956965
l.exit(err)
957966
}
958967
}

0 commit comments

Comments
 (0)