Last active
October 25, 2015 15:49
-
-
Save mjohnson9/13d43ce3a78ec76fba44 to your computer and use it in GitHub Desktop.
A trivial syslog-to-journal implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"net/http" | |
"time" | |
"github.com/jeromer/syslogparser" | |
"gopkg.in/mcuadros/go-syslog.v2" | |
) | |
func makeRequest() *io.PipeWriter { | |
pipeR, pipeW := io.Pipe() | |
r, err := http.NewRequest("POST", "http://127.0.0.1:19532/upload", pipeR) | |
if err != nil { | |
panic(err) | |
} | |
r.ContentLength = -1 | |
r.Header.Set("Content-Type", "application/vnd.fdo.journal") | |
go func() { | |
_, err := http.DefaultClient.Do(r) | |
if err != nil { | |
panic(err) | |
} | |
panic("request died") | |
}() | |
return pipeW | |
} | |
func worker(c chan syslogparser.LogParts) { | |
pipeW := makeRequest() | |
for entry := range c { | |
uploadLogEntry(entry, pipeW) | |
} | |
} | |
func main() { | |
channel := make(syslog.LogPartsChannel) | |
handler := syslog.NewChannelHandler(channel) | |
server := syslog.NewServer() | |
server.SetFormat(syslog.Automatic) | |
server.SetHandler(handler) | |
err := server.ListenUDP("0.0.0.0:514") | |
if err != nil { | |
panic(err) | |
} | |
err = server.Boot() | |
if err != nil { | |
panic(err) | |
} | |
go worker(channel) | |
server.Wait() | |
fmt.Println("Done waiting.") | |
} | |
func uploadLogEntry(logParts syslogparser.LogParts, w io.Writer) { | |
_, err := io.WriteString(w, fmt.Sprintf("__REALTIME_TIMESTAMP=%d\nMESSAGE=%s\nPRIORITY=%d\nSYSLOG_FACILITY=%d\nSYSLOG_IDENTIFIER=%s\n_HOSTNAME=%s\n\n", getTimestamp(logParts["timestamp"].(time.Time)), logParts["content"], logParts["severity"], logParts["facility"], logParts["tag"], logParts["hostname"])) | |
if err != nil { | |
panic(err) | |
} | |
} | |
func getTimestamp(t time.Time) int64 { | |
ns := t.UnixNano() | |
return ns / 1000 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment