1
0
Fork 0
mirror of https://github.com/Luzifer/elastic_cron.git synced 2024-12-22 18:31:20 +00:00

Allow log format to be configured

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2017-04-02 14:06:41 +02:00
parent 2809935b64
commit eb7c01ab2f
Signed by: luzifer
GPG key ID: DC2729FDD34BE99E
2 changed files with 40 additions and 13 deletions

View file

@ -27,6 +27,7 @@ var (
type cronConfig struct {
RSyslogTarget string `yaml:"rsyslog_target"`
LogTemplate string `yaml:"log_template"`
Jobs []cronJob `yaml:"jobs"`
}
@ -52,7 +53,9 @@ func main() {
log.Fatalf("Unable to read config file: %s")
}
cc := cronConfig{}
cc := cronConfig{
LogTemplate: `<{{ syslogpri .Severity }}>{{ .Date.Format "Jan 02 15:04:05" }} {{ .Hostname }} {{ .JobName }}: {{ .Message }}`,
}
if err := yaml.Unmarshal(body, &cc); err != nil {
log.Fatalf("Unable to parse config file: %s", err)
}
@ -68,7 +71,7 @@ func main() {
c.Start()
logadapter, err := NewSyslogAdapter(cc.RSyslogTarget)
logadapter, err := NewSyslogAdapter(cc.RSyslogTarget, cc.LogTemplate)
if err != nil {
log.Fatalf("Unable to open syslog connection: %s", err)
}

View file

@ -5,6 +5,7 @@ import (
"fmt"
"io"
"net"
"text/template"
"time"
"github.com/cenkalti/backoff"
@ -15,9 +16,10 @@ const (
tcpDialTimeout = 5 * time.Second
)
func NewSyslogAdapter(address string) (*SyslogAdapter, error) {
func NewSyslogAdapter(address, logFormat string) (*SyslogAdapter, error) {
return &SyslogAdapter{
address: address,
address: address,
logFormat: logFormat,
dialer: &net.Dialer{
Timeout: tcpDialTimeout,
},
@ -32,8 +34,32 @@ type message struct {
}
type SyslogAdapter struct {
address string
dialer *net.Dialer
address string
logFormat string
dialer *net.Dialer
}
func (a *SyslogAdapter) formatMessage(m *message) (string, error) {
t, err := template.New("logFormat").Funcs(template.FuncMap{
"syslogpri": func(pri int) int { return 16*8 + pri },
}).Parse(a.logFormat)
if err != nil {
return "", err
}
buf := bytes.NewBufferString("")
if err := t.Execute(buf, map[string]interface{}{
"Date": m.Date,
"JobName": m.JobName,
"Hostname": cfg.Hostname,
"Message": m.Message,
"Severity": m.Severity,
}); err != nil {
return "", err
}
return buf.String(), nil
}
func (a *SyslogAdapter) Stream(logstream chan *message) {
@ -49,13 +75,11 @@ func (a *SyslogAdapter) Stream(logstream chan *message) {
for msg := range logstream {
b.Reset()
fmt.Fprintf(b, "<%d>%s %s %s: %s\n",
16*8+msg.Severity,
msg.Date.Format("Jan 02 15:04:05"),
cfg.Hostname,
msg.JobName,
msg.Message,
)
msgLine, err := a.formatMessage(msg)
if err != nil {
return err
}
fmt.Fprintln(b, msgLine)
if err := conn.SetDeadline(time.Now().Add(readWriteTimeout)); err != nil {
fmt.Printf("syslog: Unable to set deadline: %s\n", err)