Skip to content

Commit f847af9

Browse files
committed
refactor(logging): Replace logr with slog
1 parent e6b3a5d commit f847af9

File tree

30 files changed

+223
-235
lines changed

30 files changed

+223
-235
lines changed

alerting/alert/alert.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ import (
44
"crypto/sha256"
55
"encoding/hex"
66
"errors"
7+
"log/slog"
78
"strconv"
89
"strings"
910
"time"
1011

11-
"github.com/TwiN/logr"
1212
"gopkg.in/yaml.v3"
1313
)
1414

@@ -131,7 +131,7 @@ func (alert *Alert) Checksum() string {
131131
func (alert *Alert) ProviderOverrideAsBytes() []byte {
132132
yamlBytes, err := yaml.Marshal(alert.ProviderOverride)
133133
if err != nil {
134-
logr.Warnf("[alert.ProviderOverrideAsBytes] Failed to marshal alert override of type=%s as bytes: %v", alert.Type, err)
134+
slog.Warn("Failed to marshal alert override as bytes", "type", alert.Type, "error", err)
135135
}
136136
return yamlBytes
137137
}

alerting/config.go

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

33
import (
4+
"log/slog"
45
"reflect"
56
"strings"
67

@@ -46,7 +47,6 @@ import (
4647
"github.com/TwiN/gatus/v5/alerting/provider/webex"
4748
"github.com/TwiN/gatus/v5/alerting/provider/zapier"
4849
"github.com/TwiN/gatus/v5/alerting/provider/zulip"
49-
"github.com/TwiN/logr"
5050
)
5151

5252
// Config is the configuration for alerting providers
@@ -186,7 +186,7 @@ func (config *Config) GetAlertingProviderByAlertType(alertType alert.Type) provi
186186
return fieldValue.Interface().(provider.AlertProvider)
187187
}
188188
}
189-
logr.Infof("[alerting.GetAlertingProviderByAlertType] No alerting provider found for alert type %s", alertType)
189+
slog.Info("No alerting provider found for alert type", "type", alertType)
190190
return nil
191191
}
192192

alerting/provider/incidentio/incidentio.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@ import (
66
"errors"
77
"fmt"
88
"io"
9+
"log/slog"
910
"net/http"
1011
"strconv"
1112
"strings"
1213

1314
"github.com/TwiN/gatus/v5/alerting/alert"
1415
"github.com/TwiN/gatus/v5/client"
1516
"github.com/TwiN/gatus/v5/config/endpoint"
16-
"github.com/TwiN/logr"
1717
"gopkg.in/yaml.v3"
1818
)
1919

@@ -117,7 +117,7 @@ func (provider *AlertProvider) Send(ep *endpoint.Endpoint, alert *alert.Alert, r
117117
err = json.NewDecoder(response.Body).Decode(&incidentioResponse)
118118
if err != nil {
119119
// Silently fail. We don't want to create tons of alerts just because we failed to parse the body.
120-
logr.Errorf("[incidentio.Send] Ran into error decoding pagerduty response: %s", err.Error())
120+
slog.Error("Error decoding incident.io response", "error", err) // TODO#1185 Why was this pagerduty response before?
121121
}
122122
alert.ResolveKey = incidentioResponse.DeduplicationKey
123123
return err
@@ -174,7 +174,7 @@ func (provider *AlertProvider) buildRequestBody(cfg *Config, ep *endpoint.Endpoi
174174
mergedMetadata[k] = v
175175
}
176176
// Add extra labels from endpoint (if present)
177-
if ep.ExtraLabels != nil && len(ep.ExtraLabels) > 0 {
177+
if ep.ExtraLabels != nil && len(ep.ExtraLabels) > 0 { // TODO: Omit nil check
178178
for k, v := range ep.ExtraLabels {
179179
mergedMetadata[k] = v
180180
}

alerting/provider/pagerduty/pagerduty.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@ import (
66
"errors"
77
"fmt"
88
"io"
9+
"log/slog"
910
"net/http"
1011

1112
"github.com/TwiN/gatus/v5/alerting/alert"
1213
"github.com/TwiN/gatus/v5/client"
1314
"github.com/TwiN/gatus/v5/config/endpoint"
14-
"github.com/TwiN/logr"
1515
"gopkg.in/yaml.v3"
1616
)
1717

@@ -105,7 +105,7 @@ func (provider *AlertProvider) Send(ep *endpoint.Endpoint, alert *alert.Alert, r
105105
var payload pagerDutyResponsePayload
106106
if err = json.NewDecoder(response.Body).Decode(&payload); err != nil {
107107
// Silently fail. We don't want to create tons of alerts just because we failed to parse the body.
108-
logr.Errorf("[pagerduty.Send] Ran into error decoding pagerduty response: %s", err.Error())
108+
slog.Error("Ran into error decoding pagerduty response", "error", err.Error())
109109
} else {
110110
alert.ResolveKey = payload.DedupKey
111111
}

api/api.go

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

33
import (
44
"io/fs"
5+
"log/slog"
56
"net/http"
67
"os"
78

@@ -10,7 +11,6 @@ import (
1011
"github.com/TwiN/gatus/v5/config/web"
1112
static "github.com/TwiN/gatus/v5/web"
1213
"github.com/TwiN/health"
13-
"github.com/TwiN/logr"
1414
fiber "github.com/gofiber/fiber/v2"
1515
"github.com/gofiber/fiber/v2/middleware/adaptor"
1616
"github.com/gofiber/fiber/v2/middleware/compress"
@@ -29,11 +29,11 @@ type API struct {
2929
func New(cfg *config.Config) *API {
3030
api := &API{}
3131
if cfg.Web == nil {
32-
logr.Warnf("[api.New] nil web config passed as parameter. This should only happen in tests. Using default web configuration")
32+
slog.Warn("nil web config passed as parameter. This should only happen in tests. Using default web configuration")
3333
cfg.Web = web.GetDefaultConfig()
3434
}
3535
if cfg.UI == nil {
36-
logr.Warnf("[api.New] nil ui config passed as parameter. This should only happen in tests. Using default ui configuration")
36+
slog.Warn("nil ui config passed as parameter. This should only happen in tests. Using default ui configuration")
3737
cfg.UI = ui.GetDefaultConfig()
3838
}
3939
api.router = api.createRouter(cfg)
@@ -47,7 +47,7 @@ func (a *API) Router() *fiber.App {
4747
func (a *API) createRouter(cfg *config.Config) *fiber.App {
4848
app := fiber.New(fiber.Config{
4949
ErrorHandler: func(c *fiber.Ctx, err error) error {
50-
logr.Errorf("[api.ErrorHandler] %s", err.Error())
50+
slog.Error("API error", slog.String("error", err.Error()))
5151
return fiber.DefaultErrorHandler(c, err)
5252
},
5353
ReadBufferSize: cfg.Web.ReadBufferSize,

api/chart.go

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

33
import (
44
"errors"
5+
"log/slog"
56
"math"
67
"net/http"
78
"net/url"
@@ -10,7 +11,6 @@ import (
1011

1112
"github.com/TwiN/gatus/v5/storage/store"
1213
"github.com/TwiN/gatus/v5/storage/store/common"
13-
"github.com/TwiN/logr"
1414
"github.com/gofiber/fiber/v2"
1515
"github.com/wcharczuk/go-chart/v2"
1616
"github.com/wcharczuk/go-chart/v2/drawing"
@@ -121,7 +121,7 @@ func ResponseTimeChart(c *fiber.Ctx) error {
121121
c.Set("Expires", "0")
122122
c.Status(http.StatusOK)
123123
if err := graph.Render(chart.SVG, c); err != nil {
124-
logr.Errorf("[api.ResponseTimeChart] Failed to render response time chart: %s", err.Error())
124+
slog.Error("Failed to render response time chart", "error", err)
125125
return c.Status(500).SendString(err.Error())
126126
}
127127
return nil

api/endpoint_status.go

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/json"
55
"errors"
66
"fmt"
7+
"log/slog"
78
"net/url"
89

910
"github.com/TwiN/gatus/v5/client"
@@ -13,7 +14,6 @@ import (
1314
"github.com/TwiN/gatus/v5/storage/store"
1415
"github.com/TwiN/gatus/v5/storage/store/common"
1516
"github.com/TwiN/gatus/v5/storage/store/common/paging"
16-
"github.com/TwiN/logr"
1717
"github.com/gofiber/fiber/v2"
1818
)
1919

@@ -27,19 +27,19 @@ func EndpointStatuses(cfg *config.Config) fiber.Handler {
2727
if !exists {
2828
endpointStatuses, err := store.Get().GetAllEndpointStatuses(paging.NewEndpointStatusParams().WithResults(page, pageSize))
2929
if err != nil {
30-
logr.Errorf("[api.EndpointStatuses] Failed to retrieve endpoint statuses: %s", err.Error())
30+
slog.Error("Failed to retrieve endpoint statuses", "error", err)
3131
return c.Status(500).SendString(err.Error())
3232
}
3333
// ALPHA: Retrieve endpoint statuses from remote instances
3434
if endpointStatusesFromRemote, err := getEndpointStatusesFromRemoteInstances(cfg.Remote); err != nil {
35-
logr.Errorf("[handler.EndpointStatuses] Silently failed to retrieve endpoint statuses from remote: %s", err.Error())
35+
slog.Error("Silently failed to retrieve endpoint statuses from remote", "error", err)
3636
} else if endpointStatusesFromRemote != nil {
3737
endpointStatuses = append(endpointStatuses, endpointStatusesFromRemote...)
3838
}
3939
// Marshal endpoint statuses to JSON
4040
data, err = json.Marshal(endpointStatuses)
4141
if err != nil {
42-
logr.Errorf("[api.EndpointStatuses] Unable to marshal object to JSON: %s", err.Error())
42+
slog.Error("Unable to marshal endpoint statuses to JSON", "error", err)
4343
return c.Status(500).SendString("unable to marshal object to JSON")
4444
}
4545
cache.SetWithTTL(fmt.Sprintf("endpoint-status-%d-%d", page, pageSize), data, cacheTTL)
@@ -61,13 +61,13 @@ func getEndpointStatusesFromRemoteInstances(remoteConfig *remote.Config) ([]*end
6161
response, err := httpClient.Get(instance.URL)
6262
if err != nil {
6363
// Log the error but continue with other instances
64-
logr.Errorf("[api.getEndpointStatusesFromRemoteInstances] Failed to retrieve endpoint statuses from %s: %s", instance.URL, err.Error())
64+
slog.Error("Failed to retrieve endpoint statuses from remote instance", "url", instance.URL, "error", err)
6565
continue
6666
}
6767
var endpointStatuses []*endpoint.Status
6868
if err = json.NewDecoder(response.Body).Decode(&endpointStatuses); err != nil {
6969
_ = response.Body.Close()
70-
logr.Errorf("[api.getEndpointStatusesFromRemoteInstances] Failed to decode endpoint statuses from %s: %s", instance.URL, err.Error())
70+
slog.Error("Failed to decode endpoint statuses from remote instance", "url", instance.URL, "error", err)
7171
continue
7272
}
7373
_ = response.Body.Close()
@@ -89,24 +89,24 @@ func EndpointStatus(cfg *config.Config) fiber.Handler {
8989
page, pageSize := extractPageAndPageSizeFromRequest(c, cfg.Storage.MaximumNumberOfResults)
9090
key, err := url.QueryUnescape(c.Params("key"))
9191
if err != nil {
92-
logr.Errorf("[api.EndpointStatus] Failed to decode key: %s", err.Error())
92+
slog.Error("Failed to decode key", "error", err)
9393
return c.Status(400).SendString("invalid key encoding")
9494
}
9595
endpointStatus, err := store.Get().GetEndpointStatusByKey(key, paging.NewEndpointStatusParams().WithResults(page, pageSize).WithEvents(1, cfg.Storage.MaximumNumberOfEvents))
9696
if err != nil {
9797
if errors.Is(err, common.ErrEndpointNotFound) {
9898
return c.Status(404).SendString(err.Error())
9999
}
100-
logr.Errorf("[api.EndpointStatus] Failed to retrieve endpoint status: %s", err.Error())
100+
slog.Error("Failed to retrieve endpoint status", "error", err)
101101
return c.Status(500).SendString(err.Error())
102102
}
103103
if endpointStatus == nil { // XXX: is this check necessary?
104-
logr.Errorf("[api.EndpointStatus] Endpoint with key=%s not found", key)
104+
slog.Error("Endpoint status not found", "key", key)
105105
return c.Status(404).SendString("not found")
106106
}
107107
output, err := json.Marshal(endpointStatus)
108108
if err != nil {
109-
logr.Errorf("[api.EndpointStatus] Unable to marshal object to JSON: %s", err.Error())
109+
slog.Error("Unable to marshal endpoint status to JSON", "error", err)
110110
return c.Status(500).SendString("unable to marshal object to JSON")
111111
}
112112
c.Set("Content-Type", "application/json")

api/external_endpoint.go

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

33
import (
44
"errors"
5+
"log/slog"
56
"strings"
67
"time"
78

@@ -11,7 +12,6 @@ import (
1112
"github.com/TwiN/gatus/v5/storage/store"
1213
"github.com/TwiN/gatus/v5/storage/store/common"
1314
"github.com/TwiN/gatus/v5/watchdog"
14-
"github.com/TwiN/logr"
1515
"github.com/gofiber/fiber/v2"
1616
)
1717

@@ -35,11 +35,11 @@ func CreateExternalEndpointResult(cfg *config.Config) fiber.Handler {
3535
key := c.Params("key")
3636
externalEndpoint := cfg.GetExternalEndpointByKey(key)
3737
if externalEndpoint == nil {
38-
logr.Errorf("[api.CreateExternalEndpointResult] External endpoint with key=%s not found", key)
38+
slog.Error("External endpoint not found", "key", key)
3939
return c.Status(404).SendString("not found")
4040
}
4141
if externalEndpoint.Token != token {
42-
logr.Errorf("[api.CreateExternalEndpointResult] Invalid token for external endpoint with key=%s", key)
42+
slog.Error("Invalid token for external endpoint", "key", key)
4343
return c.Status(401).SendString("invalid token")
4444
}
4545
// Persist the result in the storage
@@ -51,7 +51,7 @@ func CreateExternalEndpointResult(cfg *config.Config) fiber.Handler {
5151
if len(c.Query("duration")) > 0 {
5252
parsedDuration, err := time.ParseDuration(c.Query("duration"))
5353
if err != nil {
54-
logr.Errorf("[api.CreateExternalEndpointResult] Invalid duration from string=%s with error: %s", c.Query("duration"), err.Error())
54+
slog.Error("Invalid duration", "duration", c.Query("duration"), "error", err.Error())
5555
return c.Status(400).SendString("invalid duration: " + err.Error())
5656
}
5757
result.Duration = parsedDuration
@@ -64,14 +64,14 @@ func CreateExternalEndpointResult(cfg *config.Config) fiber.Handler {
6464
if errors.Is(err, common.ErrEndpointNotFound) {
6565
return c.Status(404).SendString(err.Error())
6666
}
67-
logr.Errorf("[api.CreateExternalEndpointResult] Failed to insert result in storage: %s", err.Error())
67+
slog.Error("Failed to insert endpoint result", "error", err.Error())
6868
return c.Status(500).SendString(err.Error())
6969
}
70-
logr.Infof("[api.CreateExternalEndpointResult] Successfully inserted result for external endpoint with key=%s and success=%s", c.Params("key"), success)
70+
slog.Info("Successfully inserted result for external endpoint", slog.Group("result", "key", c.Params("key"), "success", success))
7171
inEndpointMaintenanceWindow := false
7272
for _, maintenanceWindow := range externalEndpoint.MaintenanceWindows {
7373
if maintenanceWindow.IsUnderMaintenance() {
74-
logr.Debug("[api.CreateExternalEndpointResult] Under endpoint maintenance window")
74+
slog.Debug("External endpoint under maintenance window", "key", externalEndpoint.Key)
7575
inEndpointMaintenanceWindow = true
7676
}
7777
}
@@ -81,7 +81,7 @@ func CreateExternalEndpointResult(cfg *config.Config) fiber.Handler {
8181
externalEndpoint.NumberOfSuccessesInARow = convertedEndpoint.NumberOfSuccessesInARow
8282
externalEndpoint.NumberOfFailuresInARow = convertedEndpoint.NumberOfFailuresInARow
8383
} else {
84-
logr.Debug("[api.CreateExternalEndpointResult] Not handling alerting because currently in the maintenance window")
84+
slog.Debug("Not handling alerting because currently in the maintenance window", "key", externalEndpoint.Key)
8585
}
8686
if cfg.Metrics {
8787
metrics.PublishMetricsForEndpoint(convertedEndpoint, result, extraLabels)

api/spa.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ package api
33
import (
44
_ "embed"
55
"html/template"
6+
"log/slog"
67

78
"github.com/TwiN/gatus/v5/config/ui"
89
static "github.com/TwiN/gatus/v5/web"
9-
"github.com/TwiN/logr"
1010
"github.com/gofiber/fiber/v2"
1111
)
1212

@@ -26,14 +26,14 @@ func SinglePageApplication(uiConfig *ui.Config) fiber.Handler {
2626
t, err := template.ParseFS(static.FileSystem, static.IndexPath)
2727
if err != nil {
2828
// This should never happen, because ui.ValidateAndSetDefaults validates that the template works.
29-
logr.Errorf("[api.SinglePageApplication] Failed to parse template. This should never happen, because the template is validated on start. Error: %s", err.Error())
29+
slog.Error("Failed to parse template. This should never happen, because the template is validated on start.", "error", err)
3030
return c.Status(500).SendString("Failed to parse template. This should never happen, because the template is validated on start.")
3131
}
3232
c.Set("Content-Type", "text/html")
3333
err = t.Execute(c, vd)
3434
if err != nil {
3535
// This should never happen, because ui.ValidateAndSetDefaults validates that the template works.
36-
logr.Errorf("[api.SinglePageApplication] Failed to execute template. This should never happen, because the template is validated on start. Error: %s", err.Error())
36+
slog.Error("Failed to parse template. This should never happen, because the template is validated on start.", "error", err)
3737
return c.Status(500).SendString("Failed to parse template. This should never happen, because the template is validated on start.")
3838
}
3939
return c.SendStatus(200)

client/client.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"errors"
1111
"fmt"
1212
"io"
13+
"log/slog"
1314
"net"
1415
"net/http"
1516
"net/smtp"
@@ -19,7 +20,6 @@ import (
1920
"time"
2021

2122
"github.com/TwiN/gocache/v2"
22-
"github.com/TwiN/logr"
2323
"github.com/TwiN/whois"
2424
"github.com/gorilla/websocket"
2525
"github.com/ishidawataru/sctp"
@@ -163,7 +163,7 @@ func CanPerformStartTLS(address string, config *Config) (connected bool, certifi
163163
if err != nil {
164164
// We're ignoring the error, because it should have been validated on startup ValidateAndSetDefaults.
165165
// It shouldn't happen, but if it does, we'll log it... Better safe than sorry ;)
166-
logr.Errorf("[client.getHTTPClient] THIS SHOULD NOT HAPPEN. Silently ignoring invalid DNS resolver due to error: %s", err.Error())
166+
slog.Error("Should never happen: Silently ignoring invalid DNS resolver", "error", err)
167167
} else {
168168
dialer := &net.Dialer{
169169
Resolver: &net.Resolver{
@@ -464,7 +464,7 @@ func QueryDNS(queryType, queryName, url string) (connected bool, dnsRcode string
464464
m.SetQuestion(queryName, queryTypeAsUint16)
465465
r, _, err := c.Exchange(m, url)
466466
if err != nil {
467-
logr.Infof("[client.QueryDNS] Error exchanging DNS message: %v", err)
467+
slog.Info("Error exchanging DNS message", "error", err)
468468
return false, "", nil, err
469469
}
470470
connected = true

0 commit comments

Comments
 (0)