Skip to content

Commit

Permalink
permissions: allow to set custom permission bits on log files
Browse files Browse the repository at this point in the history
This adds the FileMode field to allow setting custom permission bits
on log files. We have use cases where the logs should be viewed only
by privileged.

This custom FileMode is used only if set by callers. It does not
perform validation on the passed permissions and code is kept minimal.
Callers should know what to pass.

Signed-off-by: Djalal Harouni <tixxdz@gmail.com>
  • Loading branch information
tixxdz committed Nov 29, 2022
1 parent 660bb86 commit 4d704c9
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions lumberjack.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// Note that this is v2.0 of lumberjack, and should be imported using gopkg.in
// thusly:
//
// import "gopkg.in/natefinch/lumberjack.v2"
// import "gopkg.in/natefinch/lumberjack.v2"
//
// The package name remains simply lumberjack, and the code resides at
// https://github.com/natefinch/lumberjack under the v2.0 branch.
Expand All @@ -26,6 +26,7 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"io/ioutil"
"os"
"path/filepath"
Expand Down Expand Up @@ -67,7 +68,7 @@ var _ io.WriteCloser = (*Logger)(nil)
// `/var/log/foo/server.log`, a backup created at 6:30pm on Nov 11 2016 would
// use the filename `/var/log/foo/server-2016-11-04T18-30-00.000.log`
//
// Cleaning Up Old Log Files
// # Cleaning Up Old Log Files
//
// Whenever a new logfile gets created, old log files may be deleted. The most
// recent files according to the encoded timestamp will be retained, up to a
Expand Down Expand Up @@ -108,6 +109,10 @@ type Logger struct {
// using gzip. The default is not to perform compression.
Compress bool `json:"compress" yaml:"compress"`

// FileMode is the file's mode and permission bits of the log file. If set
// it will be used as the specified mode.
FileMode fs.FileMode

size int64
file *os.File
mu sync.Mutex
Expand Down Expand Up @@ -214,6 +219,11 @@ func (l *Logger) openNew() error {

name := l.filename()
mode := os.FileMode(0644)

if l.fileModeIsSet() {
mode = l.FileMode
}

info, err := osStat(name)
if err == nil {
// Copy the mode off the old logfile.
Expand Down Expand Up @@ -298,6 +308,16 @@ func (l *Logger) filename() string {
return filepath.Join(os.TempDir(), name)
}

// fileModeIsSet checks if the file mode of the log file was set. If so
// it returns true. It does not validate the mode.
func (l *Logger) fileModeIsSet() bool {
if uint32(l.FileMode) != 0 {
return true
}

return false
}

// millRunOnce performs compression and removal of stale log files.
// Log files are compressed if enabled via configuration and old log
// files are removed, keeping at most l.MaxBackups files, as long as
Expand Down

0 comments on commit 4d704c9

Please sign in to comment.