From 61eb60885ca94c57c87e61480fd564749717fb69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Art=C5=ABras=20Knei=C5=BEys?= Date: Tue, 16 Mar 2021 19:16:49 +0200 Subject: [PATCH] Added WithPerm() --- README.md | 8 ++++++++ writer.go | 11 ++++++++++- writer_test.go | 12 ++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index da780ff..6984394 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,14 @@ w := cronowriter.MustNew("/path/to/example.log.%Y%m%d", writer.WithInit()) // /path/to/example.log.20170204 ``` +with Perm +```go +w := cronowriter.MustNew("/path/to/example.log.%Y%m%d", writer.WithPerm(os.FileMode(0600))) + +// output file with permissions +// -rw------- /path/to/example.log.20170204 +``` + ## Example using with zap ### [uber-go/zap](https://github.com/uber-go/zap) diff --git a/writer.go b/writer.go index 350dfd3..3b90669 100644 --- a/writer.go +++ b/writer.go @@ -17,6 +17,7 @@ type ( path string // current file path symlink *strftime.Strftime // symbolic link to current file path fp *os.File // current file pointer + perm os.FileMode loc *time.Location mux sync.Locker log logger @@ -48,6 +49,7 @@ func New(pattern string, options ...Option) (*CronoWriter, error) { mux: new(sync.Mutex), // default mutex enable log: &nopLogger{}, init: false, + perm: os.FileMode(0644), } for _, option := range options { @@ -132,6 +134,13 @@ func WithInit() Option { } } +// WithPerm sets permissions for created files +func WithPerm(perm os.FileMode) Option { + return func(c *CronoWriter) { + c.perm = perm + } +} + // Write writes to the file and rotate files automatically based on current date and time. func (c *CronoWriter) Write(b []byte) (int, error) { c.mux.Lock() @@ -154,7 +163,7 @@ func (c *CronoWriter) Write(b []byte) (int, error) { return c.write(nil, err) } - fp, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + fp, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, c.perm) if err != nil { return c.write(nil, err) } diff --git a/writer_test.go b/writer_test.go index 3e5a424..2fa50f8 100644 --- a/writer_test.go +++ b/writer_test.go @@ -158,6 +158,18 @@ func TestCronoWriter_Path(t *testing.T) { } } +func TestCronoWriter_Perm(t *testing.T) { + expected := os.FileMode(0600) + c := MustNew(filepath.Join(tmpDir, "test.log.%Y%m%d"), WithInit(), WithPerm(expected)) + stat, err := os.Stat(c.Path()) + if err != nil { + t.Fatal(err) + } + if stat.Mode() != expected { + t.Errorf("Expected file mode %#o, got %#o", expected, stat.Mode()) + } +} + func TestCronoWriter_WriteSymlink(t *testing.T) { stubNow("2017-02-04 16:35:05 +0900") tests := []struct {