pgterminate/notifier/syslog.go

86 lines
1.9 KiB
Go
Raw Normal View History

2018-06-24 16:10:26 +02:00
package notifier
import (
2019-02-16 11:47:30 +01:00
"log/syslog"
2018-06-24 16:10:26 +02:00
"github.com/jouir/pgterminate/base"
2018-06-24 17:49:48 +02:00
"github.com/jouir/pgterminate/log"
2018-06-24 16:10:26 +02:00
)
// Syslog notifier
type Syslog struct {
2018-07-08 23:48:48 +02:00
sessions chan *base.Session
2018-06-24 16:10:26 +02:00
ident string
2019-02-16 11:47:30 +01:00
format string
2018-06-24 16:10:26 +02:00
priority syslog.Priority
writer *syslog.Writer
}
// NewSyslog creates a syslog notifier
2019-02-16 11:47:30 +01:00
func NewSyslog(facility string, ident string, format string, sessions chan *base.Session) Notifier {
2018-06-24 16:10:26 +02:00
var priority syslog.Priority
switch facility {
case "LOCAL0":
priority = syslog.LOG_INFO | syslog.LOG_LOCAL0
case "LOCAL1":
priority = syslog.LOG_INFO | syslog.LOG_LOCAL1
case "LOCAL2":
priority = syslog.LOG_INFO | syslog.LOG_LOCAL2
case "LOCAL3":
priority = syslog.LOG_INFO | syslog.LOG_LOCAL3
case "LOCAL4":
priority = syslog.LOG_INFO | syslog.LOG_LOCAL4
case "LOCAL5":
priority = syslog.LOG_INFO | syslog.LOG_LOCAL5
case "LOCAL6":
priority = syslog.LOG_INFO | syslog.LOG_LOCAL6
default: // LOCAL7
priority = syslog.LOG_INFO | syslog.LOG_LOCAL7
}
return &Syslog{
sessions: sessions,
ident: ident,
priority: priority,
2019-02-16 11:47:30 +01:00
format: format,
2018-06-24 16:10:26 +02:00
}
}
// Run starts syslog notifier
func (s *Syslog) Run() {
2018-06-24 17:49:48 +02:00
log.Info("Starting syslog notifier")
2018-06-24 16:10:26 +02:00
var err error
if s.writer, err = syslog.New(s.priority, s.ident); err != nil {
base.Panic(err)
}
for session := range s.sessions {
2019-02-16 11:47:30 +01:00
s.writer.Info(session.Format(s.format))
2018-06-24 16:10:26 +02:00
}
}
// Reload disconnect from syslog daemon and re-connect
// Executed when receiving SIGHUP signal
func (s *Syslog) Reload() {
2018-06-24 17:49:48 +02:00
log.Info("Reloading syslog notifier")
2018-06-24 16:10:26 +02:00
if s.writer != nil {
2018-06-24 17:49:48 +02:00
log.Debug("Re-connecting to syslog daemon")
2018-06-24 16:10:26 +02:00
s.disconnect()
s.connect()
}
}
// connect to syslog daemon
func (s *Syslog) connect() {
var err error
if s.writer, err = syslog.New(s.priority, s.ident); err != nil {
base.Panic(err)
}
}
// disconnect from syslog daemon
func (s *Syslog) disconnect() {
var err error
if err = s.writer.Close(); err != nil {
base.Panic(err)
}
}