Logging: structured slog messages throughout, and WithLogger options so callers choose the logger

Log messages are lower-case event names with their details as key/value
attributes ("error" for errors), in place of formatted strings.

Loggable package take a WithLogger option as part of their "New*" call,
defaulting to slog.Default(). Each tags its lines with its `component`.

Some debug loggers print directly rather than using slog when in
terminal logging mode.
This commit is contained in:
bwilliams committed 2026-10-15 16:10:52 +01:00
1 parent 0b5fde9563
commit 043e307663
49 files changed
+598 -248

No files matched your search

+27 -3
View File
@@ -18,21 +18,45 @@ type FindATender struct {
config *config.JobSearchConfig
apiRoot string
ctx context.Context
log *slog.Logger
}
// Option configures a FindATender client.
type Option func(*FindATender)
// WithLogger makes the client log to logger instead of slog.Default().
func WithLogger(logger *slog.Logger) Option {
return func(ft *FindATender) {
ft.log = logger
}
}
// New returns a client for the OCDS API at apiRoot. Requests time out after
// 60 seconds and are retried once. Call Shutdown when finished with it.
func New(conf *config.JobSearchConfig, apiRoot string) *FindATender {
// 60 seconds and are retried once. Call Shutdown when finished with it. It
// logs to slog.Default() unless given WithLogger.
func New(conf *config.JobSearchConfig, apiRoot string, opts ...Option) *FindATender {
ft := &FindATender{
config: conf,
apiRoot: apiRoot,
}
for _, opt := range opts {
opt(ft)
}
ft.httpClient = resty.New().
SetTimeout(60 * time.Duration(time.Second)).
SetRetryCount(1)
return ft
}
// logger returns the logger the client logs to, tagged with its component.
func (ft *FindATender) logger() *slog.Logger {
log := ft.log
if log == nil {
log = slog.Default()
}
return log.With("component", "findatender")
}
// ReloadConfig replaces the configuration the client reads, such as the log
// level. The HTTP client and API root set by New are not changed.
func (ft *FindATender) ReloadConfig(conf *config.JobSearchConfig) {
@@ -55,7 +79,7 @@ func (ft *FindATender) With(ctx context.Context) *FindATender {
// logged, as there is nothing a caller could do about it.
func (ft *FindATender) Shutdown() {
if err := ft.httpClient.Close(); err != nil {
slog.Warn("findatender: closing HTTP client", "error", err)
ft.logger().Warn("closing http client failed", "error", err)
}
}