diff --git a/README.md b/README.md index 915d18c..e1419ca 100644 --- a/README.md +++ b/README.md @@ -51,9 +51,18 @@ w := writer.MustNew("/path/to/example.log.%Y%m%d", writer.WithMutex()) with Debug (stdout and stderr) ```go w := writer.MustNew("/path/to/example.log.%Y%m%d", writer.WithDebug()) +w.Write([]byte("test")) // output file, stdout and stderr -// /path/to/2017/02/04/example.log +// /path/to/example.log.20170204 +``` + +with Init +```go +w := writer.MustNew("/path/to/example.log.%Y%m%d", writer.WithInit()) + +// open the file when New() method is called +// /path/to/example.log.20170204 ``` ## Format diff --git a/writer.go b/writer.go index 1e1805a..0091932 100644 --- a/writer.go +++ b/writer.go @@ -11,13 +11,14 @@ import ( ) type cronoWriter struct { - pattern *strftime.Strftime - path string - fp *os.File + pattern *strftime.Strftime // given pattern + path string // current file path + fp *os.File // current file pointer loc *time.Location mux sync.Locker stdout io.Writer stderr io.Writer + init bool // if true, open the file when New() method is called } type option func(*cronoWriter) @@ -48,11 +49,18 @@ func New(pattern string, options ...option) (*cronoWriter, error) { mux: new(NoMutex), // default mutex off stdout: &noopWriter{}, stderr: &noopWriter{}, + init: false, } for _, option := range options { option(c) } + + if c.init { + if _, err := c.Write([]byte("")); err != nil { + return nil, err + } + } return c, nil } @@ -85,6 +93,12 @@ func WithDebug() option { } } +func WithInit() option { + return func(c *cronoWriter) { + c.init = true + } +} + func (c *cronoWriter) Write(b []byte) (int, error) { c.mux.Lock() defer c.mux.Unlock() diff --git a/writer_test.go b/writer_test.go index 9703e51..602a4c1 100644 --- a/writer_test.go +++ b/writer_test.go @@ -17,6 +17,11 @@ func stubNow(value string) { } func TestNew(t *testing.T) { + tmpDir, err := ioutil.TempDir("", "cronowriter") + if err != nil { + t.Fatal(err) + } + c, _ := New("/path/to/file") if c.pattern.Pattern() != "/path/to/file" { t.Errorf("Expected pattern file, got %s", c.pattern.Pattern()) @@ -37,10 +42,19 @@ func TestNew(t *testing.T) { t.Error("Expected mutex object, got nil") } - c, err := New("/path/to/%") + c, err = New("/path/to/%") if err == nil { t.Errorf("Expected failed compile error, got %v", err) } + + initPath := filepath.Join(tmpDir, "init_test.log") + _, err = New(initPath, WithInit()) + if err != nil { + t.Error(err) + } + if _, err := os.Stat(initPath); err != nil { + t.Error(err) + } } func TestMustNew_Panic(t *testing.T) {