Skip to content

Commit 8060a77

Browse files
garyhodgsonTwiN
andauthored
feat(logging): Allow configuring logging verbosity level (#872)
* introduces TwiN/logr library * use new features of logr library * minor tweaks and formatting * Apply suggestions from code review --------- Co-authored-by: TwiN <[email protected]>
1 parent 92bb42d commit 8060a77

File tree

6 files changed

+32
-20
lines changed

6 files changed

+32
-20
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@ If you want to test it locally, see [Docker](#docker).
216216
| Parameter | Description | Default |
217217
|:-----------------------------|:-------------------------------------------------------------------------------------------------------------------------------------|:---------------------------|
218218
| `debug` | Whether to enable debug logs. | `false` |
219+
| `log-level` | Log level: DEBUG, INFO, WARN, ERROR. | `INFO` |
219220
| `metrics` | Whether to expose metrics at `/metrics`. | `false` |
220221
| `storage` | [Storage configuration](#storage). | `{}` |
221222
| `alerting` | [Alerting configuration](#alerting). | `{}` |

config/config.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"github.com/TwiN/gatus/v5/config/web"
2323
"github.com/TwiN/gatus/v5/security"
2424
"github.com/TwiN/gatus/v5/storage"
25+
"github.com/TwiN/logr"
2526
"gopkg.in/yaml.v3"
2627
)
2728

@@ -54,6 +55,9 @@ type Config struct {
5455
// Debug Whether to enable debug logs
5556
Debug bool `yaml:"debug,omitempty"`
5657

58+
// LogLevel is one of DEBUG, INFO, WARN and ERROR. Defaults to INFO
59+
LogLevel logr.Level `yaml:"log-level,omitempty"`
60+
5761
// Metrics Whether to expose metrics at /metrics
5862
Metrics bool `yaml:"metrics,omitempty"`
5963

go.mod

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
module github.com/TwiN/gatus/v5
22

3-
go 1.22.2
3+
go 1.22.4
44

55
require (
66
code.gitea.io/sdk/gitea v0.19.0
77
github.com/TwiN/deepmerge v0.2.1
88
github.com/TwiN/g8/v2 v2.0.0
99
github.com/TwiN/gocache/v2 v2.2.2
1010
github.com/TwiN/health v1.6.0
11+
github.com/TwiN/logr v0.2.1
1112
github.com/TwiN/whois v1.1.9
1213
github.com/aws/aws-sdk-go v1.54.10
1314
github.com/coreos/go-oidc/v3 v3.11.0

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ github.com/TwiN/gocache/v2 v2.2.2 h1:4HToPfDV8FSbaYO5kkbhLpEllUYse5rAf+hVU/mSsuI
1616
github.com/TwiN/gocache/v2 v2.2.2/go.mod h1:WfIuwd7GR82/7EfQqEtmLFC3a2vqaKbs4Pe6neB7Gyc=
1717
github.com/TwiN/health v1.6.0 h1:L2ks575JhRgQqWWOfKjw9B0ec172hx7GdToqkYUycQM=
1818
github.com/TwiN/health v1.6.0/go.mod h1:Z6TszwQPMvtSiVx1QMidVRgvVr4KZGfiwqcD7/Z+3iw=
19+
github.com/TwiN/logr v0.2.1 h1:kMhUmBBVlFxzqTvyHuNoYQ/uwqg8BW4y0AyZxI5JB3Q=
20+
github.com/TwiN/logr v0.2.1/go.mod h1:oldDOkRjFXjZqiMP0+ca5NAQHXTiJ02zHirsuBJJH6k=
1921
github.com/TwiN/whois v1.1.9 h1:m20+m1CXnrstie+tW2ZmAJkfcT9zgwpVRUFsKeMw+ng=
2022
github.com/TwiN/whois v1.1.9/go.mod h1:TjipCMpJRAJYKmtz/rXQBU6UGxMh6bk8SHazu7OMnQE=
2123
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=

main.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"github.com/TwiN/gatus/v5/controller"
1313
"github.com/TwiN/gatus/v5/storage/store"
1414
"github.com/TwiN/gatus/v5/watchdog"
15+
"github.com/TwiN/logr"
1516
)
1617

1718
func main() {
@@ -23,6 +24,7 @@ func main() {
2324
if err != nil {
2425
panic(err)
2526
}
27+
configureLogging(cfg)
2628
initializeStorage(cfg)
2729
start(cfg)
2830
// Wait for termination signal
@@ -57,6 +59,11 @@ func save() {
5759
}
5860
}
5961

62+
func configureLogging(cfg *config.Config) {
63+
logr.SetThreshold(cfg.LogLevel)
64+
logr.Infof("[main.configureLogging] Log Level is %s", logr.GetThreshold())
65+
}
66+
6067
func loadConfiguration() (*config.Config, error) {
6168
configPath := os.Getenv("GATUS_CONFIG_PATH")
6269
// Backwards compatibility

watchdog/watchdog.go

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"github.com/TwiN/gatus/v5/config/maintenance"
1414
"github.com/TwiN/gatus/v5/metrics"
1515
"github.com/TwiN/gatus/v5/storage/store"
16+
"github.com/TwiN/logr"
1617
)
1718

1819
var (
@@ -31,31 +32,31 @@ func Monitor(cfg *config.Config) {
3132
if endpoint.IsEnabled() {
3233
// To prevent multiple requests from running at the same time, we'll wait for a little before each iteration
3334
time.Sleep(777 * time.Millisecond)
34-
go monitor(endpoint, cfg.Alerting, cfg.Maintenance, cfg.Connectivity, cfg.DisableMonitoringLock, cfg.Metrics, cfg.Debug, ctx)
35+
go monitor(endpoint, cfg.Alerting, cfg.Maintenance, cfg.Connectivity, cfg.DisableMonitoringLock, cfg.Metrics, ctx)
3536
}
3637
}
3738
}
3839

3940
// monitor a single endpoint in a loop
40-
func monitor(ep *endpoint.Endpoint, alertingConfig *alerting.Config, maintenanceConfig *maintenance.Config, connectivityConfig *connectivity.Config, disableMonitoringLock, enabledMetrics, debug bool, ctx context.Context) {
41+
func monitor(ep *endpoint.Endpoint, alertingConfig *alerting.Config, maintenanceConfig *maintenance.Config, connectivityConfig *connectivity.Config, disableMonitoringLock bool, enabledMetrics bool, ctx context.Context) {
4142
// Run it immediately on start
42-
execute(ep, alertingConfig, maintenanceConfig, connectivityConfig, disableMonitoringLock, enabledMetrics, debug)
43+
execute(ep, alertingConfig, maintenanceConfig, connectivityConfig, disableMonitoringLock, enabledMetrics)
4344
// Loop for the next executions
4445
for {
4546
select {
4647
case <-ctx.Done():
4748
log.Printf("[watchdog.monitor] Canceling current execution of group=%s; endpoint=%s", ep.Group, ep.Name)
4849
return
4950
case <-time.After(ep.Interval):
50-
execute(ep, alertingConfig, maintenanceConfig, connectivityConfig, disableMonitoringLock, enabledMetrics, debug)
51+
execute(ep, alertingConfig, maintenanceConfig, connectivityConfig, disableMonitoringLock, enabledMetrics)
5152
}
5253
}
5354
// Just in case somebody wandered all the way to here and wonders, "what about ExternalEndpoints?"
5455
// Alerting is checked every time an external endpoint is pushed to Gatus, so they're not monitored
5556
// periodically like they are for normal endpoints.
5657
}
5758

58-
func execute(ep *endpoint.Endpoint, alertingConfig *alerting.Config, maintenanceConfig *maintenance.Config, connectivityConfig *connectivity.Config, disableMonitoringLock, enabledMetrics, debug bool) {
59+
func execute(ep *endpoint.Endpoint, alertingConfig *alerting.Config, maintenanceConfig *maintenance.Config, connectivityConfig *connectivity.Config, disableMonitoringLock bool, enabledMetrics bool) {
5960
if !disableMonitoringLock {
6061
// By placing the lock here, we prevent multiple endpoints from being monitored at the exact same time, which
6162
// could cause performance issues and return inaccurate results
@@ -64,37 +65,33 @@ func execute(ep *endpoint.Endpoint, alertingConfig *alerting.Config, maintenance
6465
}
6566
// If there's a connectivity checker configured, check if Gatus has internet connectivity
6667
if connectivityConfig != nil && connectivityConfig.Checker != nil && !connectivityConfig.Checker.IsConnected() {
67-
log.Println("[watchdog.execute] No connectivity; skipping execution")
68+
logr.Infof("[watchdog.execute] No connectivity; skipping execution")
6869
return
6970
}
70-
if debug {
71-
log.Printf("[watchdog.execute] Monitoring group=%s; endpoint=%s", ep.Group, ep.Name)
72-
}
71+
logr.Debugf("[watchdog.execute] Monitoring group=%s; endpoint=%s", ep.Group, ep.Name)
7372
result := ep.EvaluateHealth()
7473
if enabledMetrics {
7574
metrics.PublishMetricsForEndpoint(ep, result)
7675
}
7776
UpdateEndpointStatuses(ep, result)
78-
if debug && !result.Success {
79-
log.Printf("[watchdog.execute] Monitored group=%s; endpoint=%s; success=%v; errors=%d; duration=%s; body=%s", ep.Group, ep.Name, result.Success, len(result.Errors), result.Duration.Round(time.Millisecond), result.Body)
77+
if logr.GetThreshold() == logr.LevelDebug && !result.Success {
78+
logr.Debugf("[watchdog.execute] Monitored group=%s; endpoint=%s; success=%v; errors=%d; duration=%s; body=%s", ep.Group, ep.Name, result.Success, len(result.Errors), result.Duration.Round(time.Millisecond), result.Body)
8079
} else {
81-
log.Printf("[watchdog.execute] Monitored group=%s; endpoint=%s; success=%v; errors=%d; duration=%s", ep.Group, ep.Name, result.Success, len(result.Errors), result.Duration.Round(time.Millisecond))
80+
logr.Infof("[watchdog.execute] Monitored group=%s; endpoint=%s; success=%v; errors=%d; duration=%s", ep.Group, ep.Name, result.Success, len(result.Errors), result.Duration.Round(time.Millisecond))
8281
}
8382
if !maintenanceConfig.IsUnderMaintenance() {
8483
// TODO: Consider moving this after the monitoring lock is unlocked? I mean, how much noise can a single alerting provider cause...
85-
HandleAlerting(ep, result, alertingConfig, debug)
86-
} else if debug {
87-
log.Println("[watchdog.execute] Not handling alerting because currently in the maintenance window")
88-
}
89-
if debug {
90-
log.Printf("[watchdog.execute] Waiting for interval=%s before monitoring group=%s endpoint=%s again", ep.Interval, ep.Group, ep.Name)
84+
HandleAlerting(ep, result, alertingConfig, logr.GetThreshold() == logr.LevelDebug)
85+
} else {
86+
logr.Debugf("[watchdog.execute] Not handling alerting because currently in the maintenance window")
9187
}
88+
logr.Debugf("[watchdog.execute] Waiting for interval=%s before monitoring group=%s endpoint=%s again", ep.Interval, ep.Group, ep.Name)
9289
}
9390

9491
// UpdateEndpointStatuses updates the slice of endpoint statuses
9592
func UpdateEndpointStatuses(ep *endpoint.Endpoint, result *endpoint.Result) {
9693
if err := store.Get().Insert(ep, result); err != nil {
97-
log.Println("[watchdog.UpdateEndpointStatuses] Failed to insert result in storage:", err.Error())
94+
logr.Errorf("[watchdog.UpdateEndpointStatuses] Failed to insert result in storage:", err.Error())
9895
}
9996
}
10097

0 commit comments

Comments
 (0)