package main import ( "encoding/json" "fmt" "io" "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\"}}", )) } type renderFormat int func parseRenderFormat(s string) (renderFormat, error) { switch s { case "json": return formatJSON, nil case "syslog": return formatSyslog, nil default: return 0, fmt.Errorf("Undefined format `%s`", s) } } const ( formatSyslog = iota // 0 formatJSON = iota ) func writeFormatted(w io.Writer, f renderFormat, msg format.LogParts) error { switch f { case formatSyslog: return syslogTmpl.Execute(w, msg) case formatJSON: enc := json.NewEncoder(w) enc.SetIndent("", " ") return enc.Encode(msg) } return nil }