mirror of https://github.com/caddyserver/caddy.git
logging: set file mode when the file already exist (#6391)
101d3e7
introduced a configuration option to set the log file mode.
This option was not taken into account if the file already exists,
making users having to delete their logs to have new logs created
with the right mode.
This commit is contained in:
parent
d85cc2ec10
commit
8e0d3e1ec5
|
@ -167,8 +167,18 @@ func (fw FileWriter) OpenWriter() (io.WriteCloser, error) {
|
|||
fw.RollKeepDays = 90
|
||||
}
|
||||
|
||||
f_tmp, _ := os.OpenFile(fw.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.FileMode(fw.Mode))
|
||||
// create the file if it does not exist with the right mode.
|
||||
// lumberjack will reuse the file mode across log rotation.
|
||||
f_tmp, err := os.OpenFile(fw.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.FileMode(fw.Mode))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f_tmp.Close()
|
||||
// ensure already existing files have the right mode,
|
||||
// since OpenFile will not set the mode in such case.
|
||||
if err = os.Chmod(fw.Filename, os.FileMode(fw.Mode)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &lumberjack.Logger{
|
||||
Filename: fw.Filename,
|
||||
|
|
|
@ -345,3 +345,42 @@ func TestFileModeToJSON(t *testing.T) {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileModeModification(t *testing.T) {
|
||||
m := syscall.Umask(0o000)
|
||||
defer syscall.Umask(m)
|
||||
|
||||
dir, err := os.MkdirTemp("", "caddytest")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create tempdir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
|
||||
fpath := path.Join(dir, "test.log")
|
||||
f_tmp, err := os.OpenFile(fpath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.FileMode(0600))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create test file: %v", err)
|
||||
}
|
||||
f_tmp.Close()
|
||||
|
||||
fw := FileWriter{
|
||||
Mode: 0o666,
|
||||
Filename: fpath,
|
||||
}
|
||||
|
||||
logger, err := fw.OpenWriter()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create file: %v", err)
|
||||
}
|
||||
defer logger.Close()
|
||||
|
||||
st, err := os.Stat(fpath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to check file permissions: %v", err)
|
||||
}
|
||||
|
||||
want := os.FileMode(fw.Mode)
|
||||
if st.Mode() != want {
|
||||
t.Errorf("file mode is %v, want %v", st.Mode(), want)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue