Skip to content

Commit

Permalink
fix logger unlock on panic
Browse files Browse the repository at this point in the history
  • Loading branch information
astraw99 committed Nov 20, 2021
1 parent 9ad2462 commit e6dc4fb
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions klog.go
Expand Up @@ -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))
Expand All @@ -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))
}
Expand All @@ -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)
}
}
Expand All @@ -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)
}
}
Expand Down Expand Up @@ -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()
Expand Down

0 comments on commit e6dc4fb

Please sign in to comment.