circolog/main.go

82 lines
2.2 KiB
Go
Raw Normal View History

2018-08-22 18:47:00 +02:00
package main
import (
"container/ring"
"flag"
"fmt"
"net/http"
"os"
"strconv"
2018-08-22 18:47:00 +02:00
syslog "gopkg.in/mcuadros/go-syslog.v2"
"gopkg.in/mcuadros/go-syslog.v2/format"
)
var circbuf *ring.Ring
func syslogdHandler(channel syslog.LogPartsChannel) {
for logParts := range channel {
fmt.Println(logParts)
circbuf.Value = logParts
circbuf = circbuf.Next()
}
}
2018-08-22 20:56:43 +02:00
func httpHandler(w http.ResponseWriter, r *http.Request) {
circbuf.Do(func(x interface{}) {
if x == nil {
return
}
logmsg := x.(format.LogParts)
if logmsg["message"] == nil {
return
}
c := logmsg["message"].(string)
w.Write([]byte(c))
w.Write([]byte("\n"))
})
}
2018-08-22 18:47:00 +02:00
func main() {
syslogSocketPath := flag.String("syslogd-socket", "", "The socket to listen to syslog addresses")
// dumpSocketPath := flag.String("dump-socket", "/run/buffer.sock", "The socket that user will connect to in order to receive logs")
bufsize := flag.Int("buffer-size", 1000, "Number of messages to keep")
UDPPort := flag.Int("log-port", 9514, "UDP port where to listen for syslog messages")
TCPPort := flag.Int("query-port", 9080, "TCP port where to listen for queries from the buffer")
address := flag.String("addr", "127.0.0.1", "Address to bind to")
2018-08-22 18:47:00 +02:00
flag.Parse()
if *TCPPort > 65535 || *TCPPort < 1 {
fmt.Fprintf(os.Stderr, "Error: selected query-port is out of bounds: %d\n", *TCPPort)
os.Exit(1)
}
if *UDPPort > 65535 || *UDPPort < 1 {
fmt.Fprintf(os.Stderr, "Error: selected log-port is out of bounds: %d\n", *UDPPort)
os.Exit(1)
}
2018-08-22 18:47:00 +02:00
2018-08-22 20:56:43 +02:00
channel := make(chan format.LogParts)
2018-08-22 18:47:00 +02:00
handler := syslog.NewChannelHandler(channel)
server := syslog.NewServer()
server.SetFormat(syslog.RFC5424)
server.SetHandler(handler)
if *syslogSocketPath != "" {
server.ListenUnixgram(*syslogSocketPath)
2018-08-22 21:05:37 +02:00
fmt.Printf("Binding socket `%s` [syslog]\n", *syslogSocketPath)
os.Exit(2)
2018-08-22 20:56:43 +02:00
} else {
addr := *address + ":" + strconv.Itoa(*UDPPort)
2018-08-22 21:05:37 +02:00
fmt.Printf("Binding address `%s` [syslog]\n", addr)
server.ListenUDP(addr)
2018-08-22 18:47:00 +02:00
}
circbuf = ring.New(*bufsize)
server.Boot()
go syslogdHandler(channel)
2018-08-22 20:56:43 +02:00
http.HandleFunc("/", httpHandler)
listenPortFmt := ":" + strconv.Itoa(*TCPPort)
fmt.Printf("Binding address `%s` [http]\n", listenPortFmt)
http.ListenAndServe(listenPortFmt, nil)
2018-08-22 18:47:00 +02:00
server.Wait()
}