Переглянути джерело

Don't log error if file is already closed

When closing the log-file, and the file is already
closed, there's no need to log an error.

This patch adds a `closed` boolean to check if the
file was closed, and if so, skip closing the file.
This prevents errors like this being logged:

    level=error msg="Error closing logger: invalid argument"

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Sebastiaan van Stijn 8 роки тому
батько
коміт
07b51ed300
1 змінених файлів з 18 додано та 1 видалено
  1. 18 1
      daemon/logger/loggerutils/rotatefilewriter.go

+ 18 - 1
daemon/logger/loggerutils/rotatefilewriter.go

@@ -1,6 +1,7 @@
 package loggerutils
 
 import (
+	"errors"
 	"os"
 	"strconv"
 	"sync"
@@ -11,6 +12,7 @@ import (
 // RotateFileWriter is Logger implementation for default Docker logging.
 type RotateFileWriter struct {
 	f            *os.File // store for closing
+	closed       bool
 	mu           sync.Mutex
 	capacity     int64 //maximum size of each file
 	currentSize  int64 // current size of the latest file
@@ -42,6 +44,10 @@ func NewRotateFileWriter(logPath string, capacity int64, maxFiles int) (*RotateF
 //WriteLog write log message to File
 func (w *RotateFileWriter) Write(message []byte) (int, error) {
 	w.mu.Lock()
+	if w.closed {
+		w.mu.Unlock()
+		return -1, errors.New("cannot write because the output file was closed")
+	}
 	if err := w.checkCapacityAndRotate(); err != nil {
 		w.mu.Unlock()
 		return -1, err
@@ -100,6 +106,8 @@ func rotate(name string, maxFiles int) error {
 
 // LogPath returns the location the given writer logs to.
 func (w *RotateFileWriter) LogPath() string {
+	w.mu.Lock()
+	defer w.mu.Unlock()
 	return w.f.Name()
 }
 
@@ -120,5 +128,14 @@ func (w *RotateFileWriter) NotifyRotateEvict(sub chan interface{}) {
 
 // Close closes underlying file and signals all readers to stop.
 func (w *RotateFileWriter) Close() error {
-	return w.f.Close()
+	w.mu.Lock()
+	defer w.mu.Unlock()
+	if w.closed {
+		return nil
+	}
+	if err := w.f.Close(); err != nil {
+		return err
+	}
+	w.closed = true
+	return nil
 }