From 86243bf46460cac797c9d3d6d32890c4576a514b Mon Sep 17 00:00:00 2001 From: boyska Date: Wed, 2 Jan 2019 17:29:34 +0100 Subject: [PATCH] circolog-tail has colors --- cmd/circolog-tail/main.go | 15 +++++++++++++++ formatter/format.go | 23 ++++++++++++++++++----- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/cmd/circolog-tail/main.go b/cmd/circolog-tail/main.go index 41bc920..2d335fa 100644 --- a/cmd/circolog-tail/main.go +++ b/cmd/circolog-tail/main.go @@ -14,6 +14,8 @@ import ( "git.lattuga.net/boyska/circolog/filtering" "git.lattuga.net/boyska/circolog/formatter" "github.com/gorilla/websocket" + isatty "github.com/mattn/go-isatty" + "github.com/mgutz/ansi" "gopkg.in/mcuadros/go-syslog.v2/format" "gopkg.in/mgo.v2/bson" ) @@ -24,8 +26,21 @@ func main() { backlogLimit := flag.Int("n", -1, "Limit the backlog length, defaults to no limit (-1)") var filter filtering.ExprValue flag.Var(&filter, "where", "sql-like query to filter logs") + // TODO: change to color-mode=auto/no/always + noColor := flag.Bool("no-color", false, "disable colors") + forceColor := flag.Bool("force-color", false, "force colors even on TTY") flag.Parse() + if *noColor && *forceColor { + fmt.Fprintln(os.Stderr, "Can't use both -no-color and -force-color") + flag.Usage() + os.Exit(2) + } + + if *noColor || (!isatty.IsTerminal(os.Stdout.Fd()) && !*forceColor) { + ansi.DisableColors(true) + } + interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt) var d *websocket.Dialer diff --git a/formatter/format.go b/formatter/format.go index aa8912c..86e0a09 100644 --- a/formatter/format.go +++ b/formatter/format.go @@ -7,6 +7,7 @@ import ( "text/template" "time" + "github.com/mgutz/ansi" "gopkg.in/mcuadros/go-syslog.v2/format" "gopkg.in/mgo.v2/bson" ) @@ -26,18 +27,30 @@ func init() { return dt.Format(time.RFC822) }, "sevName": func(s int) string { - names := []string{"emerg", "alert", "crit", "err", "warn", "notice", "info", "dbg"} - if s >= len(names) { + names := []string{"emerg ", "alert ", "crit ", "err ", "warn ", "notice", "info ", "dbg "} + switch { + case s < 2: // emerg..alert + return ansi.Color(names[s], "red+b") + case s < 4: // emerg..err + return ansi.Color(names[s], "red") + case s < 6: // warn..notice + return ansi.Color(names[s], "white+b") + case s >= len(names): return "???" + default: + return names[s] } - return names[s] }, + "color": func(color, text string) string { + return ansi.Color(text, color) // slow; should use colorfunc + }, + "red": ansi.ColorFunc("red+b"), } syslogTmpl = template.Must(template.New("syslog").Funcs(tmplFuncs).Parse( - "{{rfc822 (index . \"timestamp\")}} {{index . \"hostname\"}} " + + "{{color \"yellow\" (rfc822 (index . \"timestamp\")) }} {{index . \"hostname\"}} " + "{{index . \"app_name\"}}" + "{{ if (ne (index . \"proc_id\") \"-\")}}[{{index . \"proc_id\"}}]{{end}}: " + - "<{{ sevName (index . \"severity\") }}> " + + "{{ sevName (index . \"severity\") }} " + "{{index . \"message\"}}", )) }