format in "/var/log/messages style"

This commit is contained in:
boyska 2018-08-23 15:35:55 +02:00
parent 5b4e85fabb
commit 369e16d6c3
2 changed files with 43 additions and 9 deletions

View file

@ -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

41
format.go Normal file
View file

@ -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()
}