git » debian:golang-blitiri-go-log » commit dba4a5e

Fix Reopen when program changes working directory

author ThinkChaos
2020-05-20 23:54:28 UTC
committer Alberto Bertogli
2020-05-22 16:51:47 UTC
parent 00fb4d8d23d19da2f55ee7881b34dbb32520c108

Fix Reopen when program changes working directory

If the program changes directory, the given path might not be valid
anymore, since it could be relative to it.

This patch fixes that issue by storing the absolute path instead, which
will be used to Reopen.

Amended-by: Alberto Bertogli <albertito@blitiri.com.ar>
  Fixed build (a ":" was missing), extended comment and commit
  message, added tests.

log.go +7 -0
log_test.go +14 -0

diff --git a/log.go b/log.go
index eaf3770..2c6a226 100644
--- a/log.go
+++ b/log.go
@@ -103,6 +103,13 @@ func New(w io.WriteCloser) *Logger {
 
 // NewFile creates a new Logger, which writes logs to the given file.
 func NewFile(path string) (*Logger, error) {
+	// Make path absolute, so Reopen continues to work if the program changes
+	// its working directory later.
+	path, err := filepath.Abs(path)
+	if err != nil {
+		return nil, err
+	}
+
 	f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
 	if err != nil {
 		return nil, err
diff --git a/log_test.go b/log_test.go
index d6ed221..7d235cb 100644
--- a/log_test.go
+++ b/log_test.go
@@ -128,6 +128,20 @@ func TestReopen(t *testing.T) {
 	}
 	l.Infof("post reopen")
 	checkContentsMatch(t, "r", fname, `^_ log_test.go:....   post reopen\n`)
+
+	// NewFile with an absolute path should resolve it internally to a full
+	// one, so reopen can work.
+	l, err := NewFile("test-relative-file")
+	defer l.Close()
+	defer os.Remove("test-relative-file")
+
+	if err != nil {
+		t.Fatalf("failed to open file for testing: %v", err)
+	}
+	if l.fname[0] != '/' {
+		t.Fatalf("internal fname is not absolute: %q", l.fname)
+	}
+
 }
 
 type nopCloser struct {