From 369e16d6c3f138876454f6bc6e41670dff652620 Mon Sep 17 00:00:00 2001 From: boyska Date: Thu, 23 Aug 2018 15:35:55 +0200 Subject: [PATCH] format in "/var/log/messages style" --- cmd/circologd/http.go | 11 ++--------- format.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 9 deletions(-) create mode 100644 format.go diff --git a/cmd/circologd/http.go b/cmd/circologd/http.go index 3632f85..5275780 100644 --- a/cmd/circologd/http.go +++ b/cmd/circologd/http.go @@ -22,12 +22,7 @@ func getHTTPHandler(hub circolog.Hub) http.HandlerFunc { hub.Register <- client for x := range client.Messages { - logmsg := x - if logmsg["message"] == nil { - continue - } - c := logmsg["message"].(string) - w.Write([]byte(c)) + w.Write([]byte(circolog.FormatSyslog(x))) w.Write([]byte("\n")) } } @@ -67,9 +62,7 @@ func getWSHandler(hub circolog.Hub) http.HandlerFunc { if err != nil { return } - if msg, ok := message["message"]; ok { - w.Write([]byte(msg.(string))) - } + w.Write([]byte(circolog.FormatSyslog(message))) if err := w.Close(); err != nil { return diff --git a/format.go b/format.go new file mode 100644 index 0000000..6a1e083 --- /dev/null +++ b/format.go @@ -0,0 +1,41 @@ +package circolog + +import ( + "bytes" + "fmt" + "text/template" + "time" + + "gopkg.in/mcuadros/go-syslog.v2/format" +) + +// Formatter is an interface, so that multiple implementations can exist +type Formatter func(format.LogParts) string + +var tmplFuncs template.FuncMap +var syslogTmpl *template.Template + +func init() { + tmplFuncs := template.FuncMap{ + "dateFormat": func(dt time.Time, fmt string) string { + return dt.Format(fmt) + }, + "rfc822": func(dt time.Time) string { + return dt.Format(time.RFC822) + }, + } + syslogTmpl = template.Must(template.New("syslog").Funcs(tmplFuncs).Parse( + "{{rfc822 (index . \"timestamp\")}} {{index . \"hostname\"}} " + + "{{index . \"app_name\"}}" + + "{{ if (ne (index . \"proc_id\") \"-\")}}[{{index . \"proc_id\"}}]{{end}}: " + + "{{index . \"message\"}}", + )) +} + +// FormatSyslog format a message in the typical format used in /var/log/messages +func FormatSyslog(msg format.LogParts) string { + fmt.Printf("%#v\n", msg["timestamp"]) + var buf bytes.Buffer + syslogTmpl.Execute(&buf, msg) + return buf.String() +}