Skip to content

Commit

Permalink
Add WithInit option
Browse files Browse the repository at this point in the history
  • Loading branch information
utahta committed Feb 6, 2017
1 parent 3b9ad2b commit e2d6cca
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 5 deletions.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 17 additions & 3 deletions writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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()
Expand Down
16 changes: 15 additions & 1 deletion writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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) {
Expand Down

0 comments on commit e2d6cca

Please sign in to comment.