From 26d68ec746abdce03df1e98b96028d61afa60129 Mon Sep 17 00:00:00 2001 From: Vitaly Pashkov Date: Mon, 11 Dec 2017 15:03:38 +0300 Subject: [PATCH] Implement template support --- main.go | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 6e0ee87..f76e925 100644 --- a/main.go +++ b/main.go @@ -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")) } } }