From eb7c01ab2f44ad28547831b99a6a0af42ff0100f Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Sun, 2 Apr 2017 14:06:41 +0200 Subject: [PATCH] Allow log format to be configured Signed-off-by: Knut Ahlers --- main.go | 7 +++++-- syslog.go | 46 +++++++++++++++++++++++++++++++++++----------- 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/main.go b/main.go index 841b8b8..aeef5f5 100644 --- a/main.go +++ b/main.go @@ -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) } diff --git a/syslog.go b/syslog.go index 5b449a1..4f9b5af 100644 --- a/syslog.go +++ b/syslog.go @@ -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)