pgterminate/notifier/file.go

65 lines
1.3 KiB
Go
Raw Normal View History

2018-06-10 08:44:53 +02:00
package notifier
import (
"os"
2018-06-11 21:05:34 +02:00
"sync"
2018-06-10 08:44:53 +02:00
"time"
2019-02-16 11:47:30 +01:00
"github.com/jouir/pgterminate/base"
"github.com/jouir/pgterminate/log"
2018-06-10 08:44:53 +02:00
)
// File structure for file notifier
type File struct {
handle *os.File
2019-02-16 11:47:30 +01:00
format string
2018-06-10 08:44:53 +02:00
name string
2018-07-08 23:48:48 +02:00
sessions chan *base.Session
2018-06-11 21:05:34 +02:00
mutex sync.Mutex
2018-06-10 08:44:53 +02:00
}
// NewFile creates a file notifier
2019-02-16 11:47:30 +01:00
func NewFile(format string, name string, sessions chan *base.Session) Notifier {
2018-06-10 08:44:53 +02:00
return &File{
name: name,
2019-02-16 11:47:30 +01:00
format: format,
2018-06-10 08:44:53 +02:00
sessions: sessions,
}
}
// Run starts the file notifier
func (f *File) Run() {
2018-06-24 17:49:48 +02:00
log.Info("Starting file notifier")
2018-06-10 08:44:53 +02:00
f.open()
defer f.terminate()
for session := range f.sessions {
timestamp := time.Now().Format(time.RFC3339)
2019-02-16 11:47:30 +01:00
_, err := f.handle.WriteString(timestamp + " " + session.Format(f.format) + "\n")
2018-06-10 08:44:53 +02:00
base.Panic(err)
}
}
// open opens a log file
func (f *File) open() {
var err error
f.handle, err = os.OpenFile(f.name, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
base.Panic(err)
}
// Reload closes and re-open the file to be compatible with logrotate
func (f *File) Reload() {
2018-06-24 17:49:48 +02:00
log.Info("Reloading file notifier")
2018-06-11 21:05:34 +02:00
f.mutex.Lock()
defer f.mutex.Unlock()
2018-06-24 17:49:48 +02:00
log.Debugf("Re-opening log file %s\n", f.name)
2018-06-10 08:44:53 +02:00
f.handle.Close()
f.open()
}
// terminate closes the file
func (f *File) terminate() {
2018-06-24 17:49:48 +02:00
log.Debugf("Closing log file %s\n", f.name)
2018-06-10 08:44:53 +02:00
f.handle.Close()
}