Skip to content

Commit 01afaa9

Browse files
committed
use custom logger for promhttp
1 parent dfd5dc6 commit 01afaa9

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

exporter/exporter.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,7 @@ func (e *Exporter) Handler() http.Handler {
363363
// Delegate http serving to Prometheus client library, which will call collector.Collect.
364364
h := promhttp.HandlerFor(gatherers, promhttp.HandlerOpts{
365365
ErrorHandling: promhttp.ContinueOnError,
366-
// ErrorLog: e.logger, // todo(idoqo): check with prometheus/client_golang about the interface here
366+
ErrorLog: newHTTPErrorLogger(e.logger),
367367
})
368368

369369
h.ServeHTTP(w, r)

exporter/http_error_logger.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package exporter
2+
3+
import (
4+
"fmt"
5+
"github.com/pkg/errors"
6+
"github.com/prometheus/client_golang/prometheus"
7+
"log/slog"
8+
)
9+
10+
// httpErrorLogger is a wrapper around slog.Logger that can log promhttp errors (by implementing a Println method).
11+
type httpErrorLogger struct {
12+
logger *slog.Logger
13+
}
14+
15+
func newHTTPErrorLogger(logger *slog.Logger) *httpErrorLogger {
16+
return &httpErrorLogger{logger: logger}
17+
}
18+
19+
// Println implements the Println method for httpErrorHandler.
20+
func (h *httpErrorLogger) Println(v ...any) {
21+
// promhttp calls the Println() method as follows:
22+
// logger.Println(message, err) i.e., v[0] is the message (a string) and v[1] is the error (which might be prometheus.MultiError)
23+
if len(v) == 2 {
24+
msg, mok := v[0].(string)
25+
err, eok := v[1].(error)
26+
if mok && eok {
27+
multiErr := prometheus.MultiError{}
28+
if errors.As(err, &multiErr) {
29+
errCount := len(multiErr)
30+
for i, err := range multiErr {
31+
h.logger.Error(msg, "error", err, "total_errors", errCount, "error_no", i)
32+
}
33+
}
34+
}
35+
}
36+
// fallback
37+
h.logger.Error(fmt.Sprint(v...))
38+
}

exporter/server.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ func OverallTargetsHandler(exporters []*Exporter, logger *slog.Logger) http.Hand
170170
// Delegate http serving to Prometheus client library, which will call collector.Collect.
171171
h := promhttp.HandlerFor(gatherers, promhttp.HandlerOpts{
172172
ErrorHandling: promhttp.ContinueOnError,
173-
// ErrorLog: logger, // todo(idoqo): check with promhttp
173+
ErrorLog: newHTTPErrorLogger(logger),
174174
})
175175

176176
h.ServeHTTP(w, r)

0 commit comments

Comments
 (0)