Add logrotate support: reopen log file on SIGHUP

This commit is contained in:
Filipp Bondarenko 2024-05-28 09:34:26 +03:00
parent 9d3fc20e58
commit 23e88a5555
2 changed files with 28 additions and 7 deletions

View File

@ -5,13 +5,6 @@ package cmd
import (
"errors"
"fmt"
"github.com/stripe/stripe-go/v74"
"github.com/urfave/cli/v2"
"github.com/urfave/cli/v2/altsrc"
"heckel.io/ntfy/v2/log"
"heckel.io/ntfy/v2/server"
"heckel.io/ntfy/v2/user"
"heckel.io/ntfy/v2/util"
"io/fs"
"math"
"net"
@ -22,6 +15,14 @@ import (
"strings"
"syscall"
"time"
"github.com/stripe/stripe-go/v74"
"github.com/urfave/cli/v2"
"github.com/urfave/cli/v2/altsrc"
"heckel.io/ntfy/v2/log"
"heckel.io/ntfy/v2/server"
"heckel.io/ntfy/v2/user"
"heckel.io/ntfy/v2/util"
)
func init() {
@ -492,5 +493,8 @@ func reloadLogLevel(inputSource altsrc.InputSourceContext) error {
} else {
log.Info("Log level is %v", strings.ToUpper(newLevelStr))
}
if err := log.Reopen(); err != nil {
return fmt.Errorf("cannot reopen log file: %s", err.Error())
}
return nil
}

View File

@ -154,6 +154,23 @@ func SetOutput(w io.Writer) {
log.SetOutput(output)
}
func Reopen() error {
mu.Lock()
defer mu.Unlock()
if f, ok := output.(*os.File); ok {
logFile := f.Name()
f.Close()
w, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
return err
}
output = &peekLogWriter{w}
log.SetOutput(output)
}
return nil
}
// File returns the log file, if any, or an empty string otherwise
func File() string {
mu.RLock()