Compare commits

..

2 Commits

Author SHA1 Message Date
Vitaly Pashkov 57eb8d4e29 Document the new template option 2017-12-11 15:12:59 +03:00
Vitaly Pashkov 26d68ec746 Implement template support 2017-12-11 15:03:38 +03:00
2 changed files with 29 additions and 4 deletions

View File

@ -5,10 +5,13 @@ Simple GELF reader application
This is a simple application which opens a network port (currently UDP only) and receives a GELF input from Graylog or any other application. The primary purpose was to be able to filter some messages from many hosts in Graylog and output it onto this reader. Then you can process this aggregated and filtered log with (for example) fail2ban to block attackers on the router, firewall or hypervisor.
Usage:
`gelf-reader [OPTIONS]`
gelf-reader [OPTIONS]
where options is:
-listen <ip>:<port> - the address and port to listen at
-output <filename> - output to file (stdout if omit)
-template <string> - output template (default "{{TimeUnix}} {{Host}}: {{Short}}")
-version - show version and exit
All template tokens should be surrounded by a "{{" and "}}" pair. Supported template tokens:
Facility, Full, Host, Level, RawExtra, Short, TimeUnix, Version
**WARNING:** There are no authentication nor any other host restriction mechanisms, this should be only used in trusted (private and/or properly firewalled) networks.

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"))
}
}
}