diff --git a/lumberjack.go b/lumberjack.go index 1afb3f9..1d9c040 100644 --- a/lumberjack.go +++ b/lumberjack.go @@ -184,6 +184,9 @@ func (l *Logger) openNew() (*os.File, error) { // no such file or the write would put it over the MaxSize, a new file is // created. func (l *Logger) openExistingOrNew(writeLen int) (*os.File, error) { + if l.Dir == "" && l.NameFormat == "" { + return l.openNew() + } files, err := ioutil.ReadDir(l.dir()) if os.IsNotExist(err) { return l.openNew() diff --git a/lumberjack_test.go b/lumberjack_test.go index 659cc77..900d0cc 100644 --- a/lumberjack_test.go +++ b/lumberjack_test.go @@ -120,13 +120,14 @@ func TestMakeLogDir(t *testing.T) { func TestDefaultLogDir(t *testing.T) { currentTime = fakeTime dir := os.TempDir() - defer os.RemoveAll(dir) l := &Logger{ NameFormat: format, } defer l.Close() b := []byte("boo!") n, err := l.Write(b) + defer os.Remove(logFile(dir)) + isNil(err, t) equals(len(b), n, t) existsWithLen(logFile(dir), n, t) @@ -371,6 +372,39 @@ func TestLocalTime(t *testing.T) { existsWithLen(filename, n, t) } +func TestDefaultDirAndName(t *testing.T) { + currentTime = fakeTime + + l := &Logger{MaxSize: Megabyte} + defer l.Close() + b := []byte("boo!") + n, err := l.Write(b) + filename := filepath.Join(os.TempDir(), fakeTime().UTC().Format(defaultNameFormat)) + defer os.Remove(filename) + + isNil(err, t) + equals(len(b), n, t) + + existsWithLen(filename, n, t) + + err = l.Close() + isNil(err, t) + + defer newFakeTime(Day)() + + // even though the old file is under MaxSize, we should write a new file + // to prevent two processes using lumberjack from writing to the same file. + n, err = l.Write(b) + + f2 := filepath.Join(os.TempDir(), fakeTime().UTC().Format(defaultNameFormat)) + defer os.Remove(f2) + + isNil(err, t) + equals(len(b), n, t) + + existsWithLen(f2, n, t) +} + // makeTempDir creates a file with a semi-unique name in the OS temp directory. // It should be based on the name of the test, to keep parallel tests from // colliding, and must be cleaned up after the test is finished.