Skip to content

Commit dc50132

Browse files
committed
refactoring
- implement logrus - general refactoring - enable json log output as default in docker Signed-off-by: Markus Blaschke <[email protected]>
1 parent f889da5 commit dc50132

File tree

7 files changed

+414
-98
lines changed

7 files changed

+414
-98
lines changed

Dockerfile

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ RUN ./azure-scheduledevents-exporter --help
1818
# FINAL IMAGE
1919
#############################################
2020
FROM gcr.io/distroless/static
21+
22+
ENV LOG_JSON=1
23+
2124
COPY --from=build /go/src/github.com/webdevops/azure-scheduledevents-exporter/azure-scheduledevents-exporter /
2225
USER 1000
2326
ENTRYPOINT ["/azure-scheduledevents-exporter"]

config/opts.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package config
2+
3+
import (
4+
"encoding/json"
5+
log "github.com/sirupsen/logrus"
6+
"time"
7+
)
8+
9+
type (
10+
Opts struct {
11+
// logger
12+
Logger struct {
13+
Debug bool ` long:"debug" env:"DEBUG" description:"debug mode"`
14+
Verbose bool `short:"v" long:"verbose" env:"VERBOSE" description:"verbose mode"`
15+
LogJson bool ` long:"log.json" env:"LOG_JSON" description:"Switch log output to json format"`
16+
}
17+
18+
// general options
19+
ServerBind string `long:"bind" env:"SERVER_BIND" description:"Server address" default:":8080"`
20+
ScrapeTime time.Duration `long:"scrape-time" env:"SCRAPE_TIME" description:"Scrape time in seconds" default:"1m"`
21+
22+
// Api options
23+
ApiUrl string `long:"api-url" env:"API_URL" description:"Azure ScheduledEvents API URL" default:"http://169.254.169.254/metadata/scheduledevents?api-version=2017-11-01"`
24+
ApiTimeout time.Duration `long:"api-timeout" env:"API_TIMEOUT" description:"Azure API timeout (seconds)" default:"30s"`
25+
ApiErrorThreshold int `long:"api-error-threshold" env:"API_ERROR_THRESHOLD" description:"Azure API error threshold (after which app will panic)" default:"0"`
26+
27+
Notification []string `long:"notification" env:"NOTIFICATION" description:"Shoutrrr url for notifications (https://containrrr.github.io/shoutrrr/)" env-delim:" " json:"-"`
28+
NotificationMsgTemplate string `long:"notification.messagetemplate" env:"NOTIFICATION_MESSAGE_TEMPLATE" description:"Notification template" default:"%v"`
29+
30+
// metrics
31+
MetricsRequestStats bool `long:"metrics-requeststats" env:"METRICS_REQUESTSTATS" description:"Enable request stats metrics"`
32+
}
33+
)
34+
35+
func (o *Opts) GetJson() []byte {
36+
jsonBytes, err := json.Marshal(o)
37+
if err != nil {
38+
log.Panic(err)
39+
}
40+
return jsonBytes
41+
}

go.mod

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@ module github.com/webdevops/azure-scheduledevents-exporter
33
go 1.13
44

55
require (
6-
github.com/golang/protobuf v1.4.2 // indirect
76
github.com/jessevdk/go-flags v1.4.1-0.20181221193153-c0795c8afcf4
87
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
9-
github.com/prometheus/client_golang v1.6.0
10-
github.com/prometheus/common v0.10.0 // indirect
11-
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299 // indirect
8+
github.com/prometheus/client_golang v1.8.0
9+
github.com/prometheus/common v0.15.0 // indirect
10+
github.com/sirupsen/logrus v1.7.0
11+
golang.org/x/sys v0.0.0-20201113233024-12cec1faf1ba // indirect
12+
google.golang.org/protobuf v1.25.0 // indirect
1213
)

go.sum

Lines changed: 318 additions & 0 deletions
Large diffs are not rendered by default.

logger.go

Lines changed: 0 additions & 51 deletions
This file was deleted.

main.go

Lines changed: 41 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -3,66 +3,39 @@ package main
33
import (
44
"fmt"
55
"github.com/jessevdk/go-flags"
6+
log "github.com/sirupsen/logrus"
7+
"github.com/webdevops/azure-scheduledevents-exporter/config"
68
"net/url"
79
"os"
10+
"path"
11+
"runtime"
812
"strings"
9-
"time"
1013
)
1114

1215
const (
1316
Author = "webdevops.io"
1417
)
1518

1619
var (
17-
argparser *flags.Parser
18-
Logger *DaemonLogger
19-
ErrorLogger *DaemonLogger
20+
argparser *flags.Parser
21+
opts config.Opts
2022

2123
// Git version information
2224
gitCommit = "<unknown>"
2325
gitTag = "<unknown>"
2426
)
2527

26-
var opts struct {
27-
// general options
28-
ServerBind string `long:"bind" env:"SERVER_BIND" description:"Server address" default:":8080"`
29-
ScrapeTime time.Duration `long:"scrape-time" env:"SCRAPE_TIME" description:"Scrape time in seconds" default:"1m"`
30-
Verbose []bool `long:"verbose" short:"v" env:"VERBOSE" description:"Verbose mode"`
31-
32-
// Api options
33-
ApiUrl string `long:"api-url" env:"API_URL" description:"Azure ScheduledEvents API URL" default:"http://169.254.169.254/metadata/scheduledevents?api-version=2017-11-01"`
34-
ApiTimeout time.Duration `long:"api-timeout" env:"API_TIMEOUT" description:"Azure API timeout (seconds)" default:"30s"`
35-
ApiErrorThreshold int `long:"api-error-threshold" env:"API_ERROR_THRESHOLD" description:"Azure API error threshold (after which app will panic)" default:"0"`
36-
37-
// metrics
38-
MetricsRequestStats bool `long:"metrics-requeststats" env:"METRICS_REQUESTSTATS" description:"Enable request stats metrics"`
39-
}
40-
4128
func main() {
4229
initArgparser()
4330

44-
// Init logger
45-
Logger = CreateDaemonLogger(0)
46-
ErrorLogger = CreateDaemonErrorLogger(0)
31+
log.Infof("starting Azure ScheduledEvents manager v%s (%s; %s; by %v)", gitTag, gitCommit, runtime.Version(), Author)
32+
log.Info(string(opts.GetJson()))
4733

48-
// set verbosity
49-
Verbose = len(opts.Verbose) >= 1
50-
51-
Logger.Messsage("Init Azure ScheduledEvents exporter v%s (%s; by %v)", gitTag, gitCommit, Author)
52-
53-
Logger.Messsage("Starting metrics collection")
54-
Logger.Messsage(" API URL: %v", opts.ApiUrl)
55-
Logger.Messsage(" API timeout: %v", opts.ApiTimeout)
56-
Logger.Messsage(" scape time: %v", opts.ScrapeTime)
57-
if opts.ApiErrorThreshold > 0 {
58-
Logger.Messsage(" error threshold: %v", opts.ApiErrorThreshold)
59-
} else {
60-
Logger.Messsage(" error threshold: disabled")
61-
}
34+
log.Infof("starting metrics collection")
6235
setupMetricsCollection()
6336
startMetricsCollection()
6437

65-
Logger.Messsage("Starting http server on %s", opts.ServerBind)
38+
log.Infof("starting http server on %s", opts.ServerBind)
6639
startHttpServer()
6740
}
6841

@@ -81,6 +54,37 @@ func initArgparser() {
8154
}
8255
}
8356

57+
// verbose level
58+
if opts.Logger.Verbose {
59+
log.SetLevel(log.DebugLevel)
60+
}
61+
62+
// debug level
63+
if opts.Logger.Debug {
64+
log.SetReportCaller(true)
65+
log.SetLevel(log.TraceLevel)
66+
log.SetFormatter(&log.TextFormatter{
67+
CallerPrettyfier: func(f *runtime.Frame) (string, string) {
68+
s := strings.Split(f.Function, ".")
69+
funcName := s[len(s)-1]
70+
return funcName, fmt.Sprintf("%s:%d", path.Base(f.File), f.Line)
71+
},
72+
})
73+
}
74+
75+
// json log format
76+
if opts.Logger.LogJson {
77+
log.SetReportCaller(true)
78+
log.SetFormatter(&log.JSONFormatter{
79+
DisableTimestamp: true,
80+
CallerPrettyfier: func(f *runtime.Frame) (string, string) {
81+
s := strings.Split(f.Function, ".")
82+
funcName := s[len(s)-1]
83+
return funcName, fmt.Sprintf("%s:%d", path.Base(f.File), f.Line)
84+
},
85+
})
86+
}
87+
8488
// --api-url
8589
apiUrl, err := url.Parse(opts.ApiUrl)
8690
if err != nil {

metrics.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,9 @@ package main
22

33
import (
44
"encoding/json"
5-
"fmt"
65
"github.com/prometheus/client_golang/prometheus"
76
"github.com/prometheus/client_golang/prometheus/promhttp"
8-
"log"
7+
log "github.com/sirupsen/logrus"
98
"net/http"
109
"time"
1110
)
@@ -103,10 +102,10 @@ func probeCollect() {
103102
apiErrorCount++
104103

105104
if opts.ApiErrorThreshold <= 0 || apiErrorCount <= opts.ApiErrorThreshold {
106-
ErrorLogger.Error("Failed API call:", err)
105+
log.Errorf("failed API call: %v", err)
107106
return
108107
} else {
109-
panic(err.Error())
108+
log.Panic(err)
110109
}
111110
}
112111

@@ -122,7 +121,8 @@ func probeCollect() {
122121
if err == nil {
123122
eventValue = float64(notBefore.Unix())
124123
} else {
125-
ErrorLogger.Error(fmt.Sprintf("Unable to parse time \"%s\" of eventid \"%v\"", event.NotBefore, event.EventId), err)
124+
log.Errorf("failed API call: %v", err)
125+
log.Errorf("unable to parse time \"%s\" of eventid \"%v\": %v", event.NotBefore, event.EventId, err)
126126
eventValue = 0
127127
}
128128
}
@@ -154,7 +154,7 @@ func probeCollect() {
154154

155155
scheduledEventDocumentIncarnation.With(prometheus.Labels{}).Set(float64(scheduledEvents.DocumentIncarnation))
156156

157-
Logger.Verbose("Fetched %v Azure ScheduledEvents", len(scheduledEvents.Events))
157+
log.Debugf("fetched %v Azure ScheduledEvents", len(scheduledEvents.Events))
158158
}
159159

160160
func fetchApiUrl() (*AzureScheduledEventResponse, error) {

0 commit comments

Comments
 (0)