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 ( import (
"errors" "errors"
"fmt" "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" "io/fs"
"math" "math"
"net" "net"
@ -22,6 +15,14 @@ import (
"strings" "strings"
"syscall" "syscall"
"time" "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() { func init() {
@ -492,5 +493,8 @@ func reloadLogLevel(inputSource altsrc.InputSourceContext) error {
} else { } else {
log.Info("Log level is %v", strings.ToUpper(newLevelStr)) 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 return nil
} }

View File

@ -154,6 +154,23 @@ func SetOutput(w io.Writer) {
log.SetOutput(output) 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 // File returns the log file, if any, or an empty string otherwise
func File() string { func File() string {
mu.RLock() mu.RLock()