circolog/cmd/circologd/format.go

65 lines
1.3 KiB
Go
Raw Normal View History

2018-11-09 13:59:58 +01:00
package main
2018-08-23 15:35:55 +02:00
import (
2018-11-09 13:59:58 +01:00
"encoding/json"
"fmt"
"io"
2018-08-23 15:35:55 +02:00
"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\"}}",
))
}
2018-11-09 13:59:58 +01:00
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
2018-08-23 15:35:55 +02:00
}