diff --git a/klog.go b/klog.go index 45efbb075..7be3dc4d4 100644 --- a/klog.go +++ b/klog.go @@ -918,6 +918,14 @@ 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 { + os.Stderr.Write([]byte("panic observed in loggingT.output")) // Make sure the message appears somewhere. + l.mu.Unlock() // Unlock if panic occurs below (eg: #L939 Error) + os.Exit(1) // Abort the process + } + }() + if l.traceLocation.isSet() { if l.traceLocation.match(file, line) { buf.Write(stacks(false)) @@ -928,7 +936,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 +953,8 @@ 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. + logExitFunc = nil // Set `logExitFunc` nil to unlock safely. + l.mu.Unlock() l.exit(err) } } @@ -953,6 +963,8 @@ 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. + logExitFunc = nil // Set `logExitFunc` nil to unlock safely. + l.mu.Unlock() l.exit(err) } } @@ -998,7 +1010,7 @@ func (l *loggingT) output(s severity, log *logr.Logger, buf *buffer, depth int, } l.mu.Unlock() timeoutFlush(10 * time.Second) - os.Exit(255) // C++ uses -1, which is silly because it's anded with 255 anyway. + os.Exit(255) // C++ uses -1, which is silly because it's ended with 255 anyway. } l.putBuffer(buf) l.mu.Unlock()