Implement template support

This commit is contained in:
Vitaly Pashkov 2017-12-11 15:03:38 +03:00
parent 9c3a95429f
commit 26d68ec746
1 changed files with 24 additions and 2 deletions

26
main.go
View File

@ -8,23 +8,28 @@ import (
"log"
"os"
"github.com/valyala/fasttemplate"
"gopkg.in/Graylog2/go-gelf.v2/gelf"
)
const (
VERSION = "0.1.2"
VERSION = "0.2.0"
)
func main() {
var (
listenAddr string
outputFile string
stemplate string
showVersion bool
outWriter io.Writer
template *fasttemplate.Template
)
flag.StringVar(&listenAddr, "listen", "0.0.0.0:12201", "listen address")
flag.StringVar(&outputFile, "output", "", "Output file (stdout if empty)")
flag.StringVar(&stemplate, "template", "{{TimeUnix}} {{Host}}: {{Short}}",
"Output template")
flag.BoolVar(&showVersion, "version", false, "Show version and exit")
flag.Parse()
@ -33,6 +38,11 @@ func main() {
return
}
template, tplerr := fasttemplate.NewTemplate(stemplate, "{{", "}}")
if tplerr != nil {
log.Fatalf("Error parsing template\n%s", tplerr)
}
if len(outputFile) > 0 {
outFile, err := os.OpenFile(outputFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0755)
if err != nil {
@ -52,12 +62,24 @@ func main() {
fmt.Printf("Listening on %v\n", gelfReader.Addr())
msgData := make(map[string]interface{}, 8)
for {
msg, err := gelfReader.ReadMessage()
if err != nil {
log.Printf("Error reading message\n%s\n", err)
} else {
fmt.Fprintf(outWriter, "%f %v: %v\n", msg.TimeUnix, msg.Host, msg.Short)
msgData["Facility"] = msg.Facility
msgData["Full"] = msg.Full
msgData["Host"] = msg.Host
msgData["Level"] = string(msg.Level)
msgData["RawExtra"] = string(msg.RawExtra)
msgData["Short"] = msg.Short
msgData["TimeUnix"] = fmt.Sprintf("%f", msg.TimeUnix)
msgData["Version"] = msg.Version
template.Execute(outWriter, msgData)
outWriter.Write([]byte("\n"))
}
}
}