Skip to content

Commit 88fb628

Browse files
tdabasinskasbwplotka
authored andcommitted
Switch logging from glog to go-kit/log (#31)
* Add logging flags * Update log messages in main * Further updates to log messages * Config package logging updated * Update template and notify logs * Show possible values for log params * Ensure a single logger is created * Remove blank line * Update log level * Update log messages * Move logger setup to a separate func * Update pkg/notify/notify.go Co-Authored-By: tdabasinskas <tomas@dabasinskas.net> * Update pkg/notify/notify.go Co-Authored-By: tdabasinskas <tomas@dabasinskas.net> * Update cmd/jiralert/main.go Co-Authored-By: tdabasinskas <tomas@dabasinskas.net> * Update pkg/config/config.go Co-Authored-By: tdabasinskas <tomas@dabasinskas.net> * Update pkg/notify/notify.go Co-Authored-By: tdabasinskas <tomas@dabasinskas.net> * Apply suggestions from code review Co-Authored-By: tdabasinskas <tomas@dabasinskas.net>
1 parent efb01aa commit 88fb628

File tree

6 files changed

+123
-89
lines changed

6 files changed

+123
-89
lines changed

cmd/jiralert/main.go

Lines changed: 54 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,25 @@ import (
1313
"github.com/free/jiralert/pkg/config"
1414
"github.com/free/jiralert/pkg/notify"
1515
"github.com/free/jiralert/pkg/template"
16+
"github.com/go-kit/kit/log"
17+
"github.com/go-kit/kit/log/level"
1618

1719
_ "net/http/pprof"
1820

19-
log "github.com/golang/glog"
2021
"github.com/prometheus/client_golang/prometheus/promhttp"
2122
)
2223

2324
const (
2425
unknownReceiver = "<unknown>"
26+
logFormatLogfmt = "logfmt"
27+
logFormatJson = "json"
2528
)
2629

2730
var (
2831
listenAddress = flag.String("listen-address", ":9097", "The address to listen on for HTTP requests.")
2932
configFile = flag.String("config", "config/jiralert.yml", "The JIRAlert configuration file")
33+
logLevel = flag.String("log.level", "info", "Log filtering level (debug, info, warn, error)")
34+
logFormat = flag.String("log.format", logFormatLogfmt, "Log format to use (" + logFormatLogfmt + ", " + logFormatJson + ")")
3035

3136
// Version is the build version, set by make to latest git tag/hash via `-ldflags "-X main.Version=$(VERSION)"`.
3237
Version = "<local build>"
@@ -38,64 +43,62 @@ func main() {
3843
runtime.SetMutexProfileFraction(1)
3944
}
4045

41-
// Override -alsologtostderr default value.
42-
if alsoLogToStderr := flag.Lookup("alsologtostderr"); alsoLogToStderr != nil {
43-
alsoLogToStderr.DefValue = "true"
44-
alsoLogToStderr.Value.Set("true")
45-
}
4646
flag.Parse()
4747

48-
log.Infof("Starting JIRAlert version %s", Version)
48+
var logger = setupLogger(*logLevel, *logFormat)
49+
level.Info(logger).Log("msg", "starting JIRAlert", "version", Version)
4950

50-
config, _, err := config.LoadFile(*configFile)
51+
config, _, err := config.LoadFile(*configFile, logger)
5152
if err != nil {
52-
log.Fatalf("Error loading configuration: %s", err)
53+
level.Error(logger).Log("msg", "error loading configuration", "path", *configFile, "err", err)
54+
os.Exit(1)
5355
}
5456

55-
tmpl, err := template.LoadTemplate(config.Template)
57+
tmpl, err := template.LoadTemplate(config.Template, logger)
5658
if err != nil {
57-
log.Fatalf("Error loading templates from %s: %s", config.Template, err)
59+
level.Error(logger).Log("msg", "error loading templates", "path", config.Template, "err", err)
60+
os.Exit(1)
5861
}
5962

6063
http.HandleFunc("/alert", func(w http.ResponseWriter, req *http.Request) {
61-
log.V(1).Infof("Handling /alert webhook request")
64+
level.Debug(logger).Log("msg", "handling /alert webhook request")
6265
defer req.Body.Close()
6366

6467
// https://godoc.org/github.com/prometheus/alertmanager/template#Data
6568
data := alertmanager.Data{}
6669
if err := json.NewDecoder(req.Body).Decode(&data); err != nil {
67-
errorHandler(w, http.StatusBadRequest, err, unknownReceiver, &data)
70+
errorHandler(w, http.StatusBadRequest, err, unknownReceiver, &data, logger)
6871
return
6972
}
7073

7174
conf := config.ReceiverByName(data.Receiver)
7275
if conf == nil {
73-
errorHandler(w, http.StatusNotFound, fmt.Errorf("receiver missing: %s", data.Receiver), unknownReceiver, &data)
76+
errorHandler(w, http.StatusNotFound, fmt.Errorf("receiver missing: %s", data.Receiver), unknownReceiver, &data, logger)
7477
return
7578
}
76-
log.V(1).Infof("Matched receiver: %q", conf.Name)
79+
level.Debug(logger).Log("msg", " matched receiver", "receiver", conf.Name)
7780

7881
// Filter out resolved alerts, not interested in them.
7982
alerts := data.Alerts.Firing()
8083
if len(alerts) < len(data.Alerts) {
81-
log.Warningf("Please set \"send_resolved: false\" on receiver %s in the Alertmanager config", conf.Name)
84+
level.Warn(logger).Log("msg", "receiver should have \"send_resolved: false\" set in Alertmanager config", "receiver", conf.Name)
8285
data.Alerts = alerts
8386
}
8487

8588
if len(data.Alerts) > 0 {
8689
r, err := notify.NewReceiver(conf, tmpl)
8790
if err != nil {
88-
errorHandler(w, http.StatusInternalServerError, err, conf.Name, &data)
91+
errorHandler(w, http.StatusInternalServerError, err, conf.Name, &data, logger)
8992
return
9093
}
91-
if retry, err := r.Notify(&data); err != nil {
94+
if retry, err := r.Notify(&data, logger); err != nil {
9295
var status int
9396
if retry {
9497
status = http.StatusServiceUnavailable
9598
} else {
9699
status = http.StatusInternalServerError
97100
}
98-
errorHandler(w, status, err, conf.Name, &data)
101+
errorHandler(w, status, err, conf.Name, &data, logger)
99102
return
100103
}
101104
}
@@ -112,11 +115,15 @@ func main() {
112115
*listenAddress = ":" + os.Getenv("PORT")
113116
}
114117

115-
log.Infof("Listening on %s", *listenAddress)
116-
log.Fatal(http.ListenAndServe(*listenAddress, nil))
118+
level.Info(logger).Log("msg", "listening", "address", *listenAddress)
119+
err = http.ListenAndServe(*listenAddress, nil)
120+
if err != nil {
121+
level.Error(logger).Log("msg", "failed to start HTTP server", "address", *listenAddress)
122+
os.Exit(1)
123+
}
117124
}
118125

119-
func errorHandler(w http.ResponseWriter, status int, err error, receiver string, data *alertmanager.Data) {
126+
func errorHandler(w http.ResponseWriter, status int, err error, receiver string, data *alertmanager.Data, logger log.Logger) {
120127
w.WriteHeader(status)
121128

122129
response := struct {
@@ -133,6 +140,30 @@ func errorHandler(w http.ResponseWriter, status int, err error, receiver string,
133140
json := string(bytes[:])
134141
fmt.Fprint(w, json)
135142

136-
log.Errorf("%d %s: err=%s receiver=%q groupLabels=%+v", status, http.StatusText(status), err, receiver, data.GroupLabels)
143+
level.Error(logger).Log("msg", "error handling request", "statusCode", status, "statusText", http.StatusText(status), "err", err, "receiver", receiver, "groupLabels", data.GroupLabels)
137144
requestTotal.WithLabelValues(receiver, strconv.FormatInt(int64(status), 10)).Inc()
138145
}
146+
147+
func setupLogger(lvl string, fmt string) (logger log.Logger) {
148+
var filter level.Option
149+
switch lvl {
150+
case "error":
151+
filter = level.AllowError()
152+
case "warn":
153+
filter = level.AllowWarn()
154+
case "debug":
155+
filter = level.AllowDebug()
156+
case "info":
157+
default:
158+
filter = level.AllowInfo()
159+
}
160+
161+
if fmt == logFormatJson {
162+
logger = log.NewJSONLogger(log.NewSyncWriter(os.Stderr))
163+
} else {
164+
logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
165+
}
166+
logger = level.NewFilter(logger, filter)
167+
logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller)
168+
return
169+
}

go.mod

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ require (
44
github.com/andygrunwald/go-jira v0.0.0-20181018203616-bbce4afa5493
55
github.com/beorn7/perks v0.0.0-20160804104726-4c0e84591b9a // indirect
66
github.com/fatih/structs v0.0.0-20171020064819-f5faa72e7309 // indirect
7-
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b
7+
github.com/go-kit/kit v0.8.0
8+
github.com/go-logfmt/logfmt v0.4.0 // indirect
9+
github.com/go-stack/stack v1.8.0 // indirect
810
github.com/golang/protobuf v0.0.0-20171021043952-1643683e1b54 // indirect
911
github.com/google/go-querystring v0.0.0-20170111101155-53e6ce116135 // indirect
1012
github.com/kr/pretty v0.1.0 // indirect
@@ -16,7 +18,6 @@ require (
1618
github.com/prometheus/procfs v0.0.0-20171017214025-a6e9df898b13 // indirect
1719
github.com/trivago/tgo v1.0.1
1820
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6 // indirect
19-
golang.org/x/tools v0.0.0-20190315214010-f0bfdbff1f9c // indirect
2021
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
2122
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7
2223
)

go.sum

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,18 @@ github.com/beorn7/perks v0.0.0-20160804104726-4c0e84591b9a h1:BtpsbiV638WQZwhA98
44
github.com/beorn7/perks v0.0.0-20160804104726-4c0e84591b9a/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
55
github.com/fatih/structs v0.0.0-20171020064819-f5faa72e7309 h1:yetGKN1jYaaVt+q69KPz+V2Z64OyTw/KfTNQS90n/tU=
66
github.com/fatih/structs v0.0.0-20171020064819-f5faa72e7309/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
7-
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
8-
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
7+
github.com/go-kit/kit v0.8.0 h1:Wz+5lgoB0kkuqLEc6NVmwRknTKP6dTGbSqvhZtBI/j0=
8+
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
9+
github.com/go-logfmt/logfmt v0.4.0 h1:MP4Eh7ZCb31lleYCFuwm0oe4/YGak+5l1vA2NOE80nA=
10+
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
11+
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
12+
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
913
github.com/golang/protobuf v0.0.0-20171021043952-1643683e1b54 h1:nRNJXiJvemchkOTn0V4U11TZkvacB94gTzbTZbSA7Rw=
1014
github.com/golang/protobuf v0.0.0-20171021043952-1643683e1b54/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
1115
github.com/google/go-querystring v0.0.0-20170111101155-53e6ce116135 h1:zLTLjkaOFEFIOxY5BWLFLwh+cL8vOBW4XJ2aqLE/Tf0=
1216
github.com/google/go-querystring v0.0.0-20170111101155-53e6ce116135/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
17+
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515 h1:T+h1c/A9Gawja4Y9mFVWj2vyii2bbUNDw3kt9VxK2EY=
18+
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
1319
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
1420
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
1521
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
@@ -29,14 +35,8 @@ github.com/prometheus/procfs v0.0.0-20171017214025-a6e9df898b13 h1:leRfx9kcgnSDk
2935
github.com/prometheus/procfs v0.0.0-20171017214025-a6e9df898b13/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
3036
github.com/trivago/tgo v1.0.1 h1:bxatjJIXNIpV18bucU4Uk/LaoxvxuOlp/oowRHyncLQ=
3137
github.com/trivago/tgo v1.0.1/go.mod h1:w4dpD+3tzNIIiIfkWWa85w5/B77tlvdZckQ+6PkFnhc=
32-
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
33-
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
3438
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6 h1:bjcUS9ztw9kFmmIxJInhon/0Is3p+EHBKNgquIzo1OI=
3539
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
36-
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
37-
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
38-
golang.org/x/tools v0.0.0-20190315214010-f0bfdbff1f9c h1:KQ2sRfnx/Xk0E4v13yE9v3gCXAn6qieU1aiQOsbmpQg=
39-
golang.org/x/tools v0.0.0-20190315214010-f0bfdbff1f9c/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
4040
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
4141
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
4242
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7 h1:+t9dhfO+GNOIGJof6kPOAenx7YgrZMTdRPV+EsnPabk=

pkg/config/config.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ package config
22

33
import (
44
"fmt"
5+
"github.com/go-kit/kit/log"
6+
"github.com/go-kit/kit/log/level"
57
"io/ioutil"
68
"net/url"
79
"path/filepath"
@@ -10,7 +12,6 @@ import (
1012
"strings"
1113
"time"
1214

13-
log "github.com/golang/glog"
1415
"github.com/trivago/tgo/tcontainer"
1516
"gopkg.in/yaml.v2"
1617
)
@@ -39,13 +40,12 @@ func Load(s string) (*Config, error) {
3940
if err != nil {
4041
return nil, err
4142
}
42-
log.V(1).Infof("Loaded config:\n%+v", cfg)
4343
return cfg, nil
4444
}
4545

4646
// LoadFile parses the given YAML file into a Config.
47-
func LoadFile(filename string) (*Config, []byte, error) {
48-
log.V(1).Infof("Loading configuration from %q", filename)
47+
func LoadFile(filename string, logger log.Logger) (*Config, []byte, error) {
48+
level.Info(logger).Log("msg", "loading configuration", "path", filename)
4949
content, err := ioutil.ReadFile(filename)
5050
if err != nil {
5151
return nil, nil, err
@@ -55,19 +55,19 @@ func LoadFile(filename string) (*Config, []byte, error) {
5555
return nil, nil, err
5656
}
5757

58-
resolveFilepaths(filepath.Dir(filename), cfg)
58+
resolveFilepaths(filepath.Dir(filename), cfg, logger)
5959
return cfg, content, nil
6060
}
6161

6262
// resolveFilepaths joins all relative paths in a configuration
6363
// with a given base directory.
64-
func resolveFilepaths(baseDir string, cfg *Config) {
64+
func resolveFilepaths(baseDir string, cfg *Config, logger log.Logger) {
6565
join := func(fp string) string {
6666
if len(fp) == 0 || filepath.IsAbs(fp) {
6767
return fp
6868
}
6969
absFp := filepath.Join(baseDir, fp)
70-
log.V(2).Infof("Relative path %q resolved to %q", fp, absFp)
70+
level.Debug(logger).Log("msg", "resolved relative configuration path", "relativePath", fp, "absolutePath", absFp)
7171
return absFp
7272
}
7373

0 commit comments

Comments
 (0)