Skip to content

Commit e42eb81

Browse files
committed
Add structured logging support to promhttp
In order to better support the standard library `log/slog` add a new interface to the `promhttp` `HandlerOpts`. Signed-off-by: SuperQ <superq@gmail.com>
1 parent dbf72fc commit e42eb81

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

prometheus/promhttp/http.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,9 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO
168168
if opts.ErrorLog != nil {
169169
opts.ErrorLog.Println("error gathering metrics:", err)
170170
}
171+
if opts.StructuredErrorLog != nil {
172+
opts.StructuredErrorLog.Error("error gathering metrics", "error", err)
173+
}
171174
errCnt.WithLabelValues("gathering").Inc()
172175
switch opts.ErrorHandling {
173176
case PanicOnError:
@@ -197,6 +200,9 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO
197200
if opts.ErrorLog != nil {
198201
opts.ErrorLog.Println("error getting writer", err)
199202
}
203+
if opts.StructuredErrorLog != nil {
204+
opts.StructuredErrorLog.Error("error getting writer", "error", err)
205+
}
200206
w = io.Writer(rsp)
201207
encodingHeader = string(Identity)
202208
}
@@ -218,6 +224,9 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO
218224
if opts.ErrorLog != nil {
219225
opts.ErrorLog.Println("error encoding and sending metric family:", err)
220226
}
227+
if opts.StructuredErrorLog != nil {
228+
opts.StructuredErrorLog.Error("error encoding and sending metric family", "error", err)
229+
}
221230
errCnt.WithLabelValues("encoding").Inc()
222231
switch opts.ErrorHandling {
223232
case PanicOnError:
@@ -344,6 +353,12 @@ type Logger interface {
344353
Println(v ...interface{})
345354
}
346355

356+
// StructuredLogger is a minimal interface HandlerOpts needs for structured
357+
// logging. This is implementd by the standard library log/slog.Logger type.
358+
type StructuredLogger interface {
359+
Error(msg string, args ...any)
360+
}
361+
347362
// HandlerOpts specifies options how to serve metrics via an http.Handler. The
348363
// zero value of HandlerOpts is a reasonable default.
349364
type HandlerOpts struct {
@@ -354,6 +369,9 @@ type HandlerOpts struct {
354369
// latter, create a Logger implementation that detects a
355370
// prometheus.MultiError and formats the contained errors into one line.
356371
ErrorLog Logger
372+
// StructuredErrorLog StructuredLogger specifies an optional structured log
373+
// handler.
374+
StructuredErrorLog StructuredLogger
357375
// ErrorHandling defines how errors are handled. Note that errors are
358376
// logged regardless of the configured ErrorHandling provided ErrorLog
359377
// is not nil.

0 commit comments

Comments
 (0)