Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8e2422d

Browse files
authored
feat: use named loggers in coderd (#8148)
1 parent 1417c12 commit 8e2422d

File tree

7 files changed

+63
-19
lines changed

7 files changed

+63
-19
lines changed

coderd/autobuild/lifecycle_executor.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ func NewExecutor(ctx context.Context, db database.Store, tss *atomic.Pointer[sch
4545
db: db,
4646
templateScheduleStore: tss,
4747
tick: tick,
48-
log: log,
48+
log: log.Named("autobuild"),
4949
}
5050
return le
5151
}
@@ -166,7 +166,7 @@ func (e *Executor) runOnce(t time.Time) Stats {
166166
Reason(reason)
167167

168168
if _, _, err := builder.Build(e.ctx, tx, nil); err != nil {
169-
log.Error(e.ctx, "unable to transition workspace",
169+
log.Error(e.ctx, "workspace build error",
170170
slog.F("transition", nextTransition),
171171
slog.Error(err),
172172
)

coderd/prometheusmetrics/aggregator.go

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ const (
2222
)
2323

2424
const (
25+
loggerName = "prometheusmetrics"
26+
2527
sizeCollectCh = 10
2628
sizeUpdateCh = 1024
2729

@@ -118,7 +120,7 @@ func NewMetricsAggregator(logger slog.Logger, registerer prometheus.Registerer,
118120
}
119121

120122
return &MetricsAggregator{
121-
log: logger,
123+
log: logger.Named(loggerName),
122124
metricsCleanupInterval: metricsCleanupInterval,
123125

124126
collectCh: make(chan (chan []prometheus.Metric), sizeCollectCh),
@@ -141,7 +143,7 @@ func (ma *MetricsAggregator) Run(ctx context.Context) func() {
141143
for {
142144
select {
143145
case req := <-ma.updateCh:
144-
ma.log.Debug(ctx, "metrics aggregator: update metrics")
146+
ma.log.Debug(ctx, "update metrics")
145147

146148
timer := prometheus.NewTimer(ma.updateHistogram)
147149
UpdateLoop:
@@ -167,7 +169,7 @@ func (ma *MetricsAggregator) Run(ctx context.Context) func() {
167169

168170
timer.ObserveDuration()
169171
case outputCh := <-ma.collectCh:
170-
ma.log.Debug(ctx, "metrics aggregator: collect metrics")
172+
ma.log.Debug(ctx, "collect metrics")
171173

172174
output := make([]prometheus.Metric, 0, len(ma.queue))
173175
for _, m := range ma.queue {
@@ -181,7 +183,7 @@ func (ma *MetricsAggregator) Run(ctx context.Context) func() {
181183
outputCh <- output
182184
close(outputCh)
183185
case <-cleanupTicker.C:
184-
ma.log.Debug(ctx, "metrics aggregator: clean expired metrics")
186+
ma.log.Debug(ctx, "clean expired metrics")
185187

186188
timer := prometheus.NewTimer(ma.cleanupHistogram)
187189

@@ -209,7 +211,7 @@ func (ma *MetricsAggregator) Run(ctx context.Context) func() {
209211
cleanupTicker.Reset(ma.metricsCleanupInterval)
210212

211213
case <-ctx.Done():
212-
ma.log.Debug(ctx, "metrics aggregator: is stopped")
214+
ma.log.Debug(ctx, "metrics aggregator is stopped")
213215
return
214216
}
215217
}
@@ -233,7 +235,7 @@ func (ma *MetricsAggregator) Collect(ch chan<- prometheus.Metric) {
233235
select {
234236
case ma.collectCh <- output:
235237
default:
236-
ma.log.Error(context.Background(), "metrics aggregator: collect queue is full")
238+
ma.log.Error(context.Background(), "collect queue is full")
237239
return
238240
}
239241

@@ -255,9 +257,9 @@ func (ma *MetricsAggregator) Update(ctx context.Context, username, workspaceName
255257
timestamp: time.Now(),
256258
}:
257259
case <-ctx.Done():
258-
ma.log.Debug(ctx, "metrics aggregator: update request is canceled")
260+
ma.log.Debug(ctx, "update request is canceled")
259261
default:
260-
ma.log.Error(ctx, "metrics aggregator: update queue is full")
262+
ma.log.Error(ctx, "update queue is full")
261263
}
262264
}
263265

coderd/provisionerdserver/provisionerdserver.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -506,7 +506,7 @@ func (server *Server) UpdateJob(ctx context.Context, request *proto.UpdateJobReq
506506
err = server.Pubsub.Publish(provisionersdk.ProvisionerJobLogsNotifyChannel(parsedID), data)
507507
if err != nil {
508508
server.Logger.Error(ctx, "failed to publish job logs", slog.F("job_id", parsedID), slog.Error(err))
509-
return nil, xerrors.Errorf("publish job log: %w", err)
509+
return nil, xerrors.Errorf("publish job logs: %w", err)
510510
}
511511
server.Logger.Debug(ctx, "published job logs", slog.F("job_id", parsedID))
512512
}

coderd/userauth.go

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ import (
3030
"github.com/coder/coder/codersdk"
3131
)
3232

33+
const (
34+
userAuthLoggerName = "userauth"
35+
)
36+
3337
// Authenticates the user with an email and password.
3438
//
3539
// @Summary Log in user
@@ -59,11 +63,14 @@ func (api *API) postLogin(rw http.ResponseWriter, r *http.Request) {
5963
return
6064
}
6165

66+
logger := api.Logger.Named(userAuthLoggerName)
67+
6268
//nolint:gocritic // In order to login, we need to get the user first!
6369
user, err := api.Database.GetUserByEmailOrUsername(dbauthz.AsSystemRestricted(ctx), database.GetUserByEmailOrUsernameParams{
6470
Email: loginWithPassword.Email,
6571
})
6672
if err != nil && !xerrors.Is(err, sql.ErrNoRows) {
73+
logger.Error(ctx, "unable to fetch user by email", slog.Error(err))
6774
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
6875
Message: "Internal error.",
6976
})
@@ -75,6 +82,7 @@ func (api *API) postLogin(rw http.ResponseWriter, r *http.Request) {
7582
// If the user doesn't exist, it will be a default struct.
7683
equal, err := userpassword.Compare(string(user.HashedPassword), loginWithPassword.Password)
7784
if err != nil {
85+
logger.Error(ctx, "unable to compare passwords", slog.Error(err))
7886
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
7987
Message: "Internal error.",
8088
})
@@ -108,6 +116,7 @@ func (api *API) postLogin(rw http.ResponseWriter, r *http.Request) {
108116
//nolint:gocritic // System needs to fetch user roles in order to login user.
109117
roles, err := api.Database.GetAuthorizationUserRoles(dbauthz.AsSystemRestricted(ctx), user.ID)
110118
if err != nil {
119+
logger.Error(ctx, "unable to fetch authorization user roles", slog.Error(err))
111120
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
112121
Message: "Internal error.",
113122
})
@@ -137,6 +146,7 @@ func (api *API) postLogin(rw http.ResponseWriter, r *http.Request) {
137146
DeploymentValues: api.DeploymentValues,
138147
})
139148
if err != nil {
149+
logger.Error(ctx, "unable to create API key", slog.Error(err))
140150
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
141151
Message: "Failed to create API key.",
142152
Detail: err.Error(),
@@ -188,8 +198,11 @@ func (api *API) postLogout(rw http.ResponseWriter, r *http.Request) {
188198
apiKey := httpmw.APIKey(r)
189199
aReq.Old = apiKey
190200

201+
logger := api.Logger.Named(userAuthLoggerName)
202+
191203
err := api.Database.DeleteAPIKeyByID(ctx, apiKey.ID)
192204
if err != nil {
205+
logger.Error(ctx, "unable to delete API key", slog.F("api_key", apiKey.ID), slog.Error(err))
193206
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
194207
Message: "Internal error deleting API key.",
195208
Detail: err.Error(),
@@ -203,6 +216,7 @@ func (api *API) postLogout(rw http.ResponseWriter, r *http.Request) {
203216
// to access the app again.
204217
err = api.Database.DeleteApplicationConnectAPIKeysByUserID(ctx, apiKey.UserID)
205218
if err != nil {
219+
logger.Error(ctx, "unable to invalidate subdomain app tokens", slog.F("user_id", apiKey.UserID), slog.Error(err))
206220
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
207221
Message: "Internal error deleting app tokens.",
208222
Detail: err.Error(),
@@ -293,11 +307,14 @@ func (api *API) userOAuth2Github(rw http.ResponseWriter, r *http.Request) {
293307

294308
oauthClient := oauth2.NewClient(ctx, oauth2.StaticTokenSource(state.Token))
295309

310+
logger := api.Logger.Named(userAuthLoggerName)
311+
296312
var selectedMemberships []*github.Membership
297313
var organizationNames []string
298314
if !api.GithubOAuth2Config.AllowEveryone {
299315
memberships, err := api.GithubOAuth2Config.ListOrganizationMemberships(ctx, oauthClient)
300316
if err != nil {
317+
logger.Error(ctx, "unable to list organization members", slog.Error(err))
301318
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
302319
Message: "Internal error fetching authenticated Github user organizations.",
303320
Detail: err.Error(),
@@ -328,6 +345,7 @@ func (api *API) userOAuth2Github(rw http.ResponseWriter, r *http.Request) {
328345

329346
ghUser, err := api.GithubOAuth2Config.AuthenticatedUser(ctx, oauthClient)
330347
if err != nil {
348+
logger.Error(ctx, "oauth2: unable to fetch authenticated user", slog.Error(err))
331349
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
332350
Message: "Internal error fetching authenticated Github user.",
333351
Detail: err.Error(),
@@ -366,6 +384,7 @@ func (api *API) userOAuth2Github(rw http.ResponseWriter, r *http.Request) {
366384

367385
emails, err := api.GithubOAuth2Config.ListEmails(ctx, oauthClient)
368386
if err != nil {
387+
logger.Error(ctx, "oauth2: unable to list emails", slog.Error(err))
369388
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
370389
Message: "Internal error fetching personal Github user.",
371390
Detail: err.Error(),
@@ -390,6 +409,7 @@ func (api *API) userOAuth2Github(rw http.ResponseWriter, r *http.Request) {
390409

391410
user, link, err := findLinkedUser(ctx, api.Database, githubLinkedID(ghUser), verifiedEmail.GetEmail())
392411
if err != nil {
412+
logger.Error(ctx, "oauth2: unable to find linked user", slog.F("gh_user", ghUser.Name), slog.Error(err))
393413
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
394414
Message: "Failed to find linked user.",
395415
Detail: err.Error(),
@@ -423,6 +443,7 @@ func (api *API) userOAuth2Github(rw http.ResponseWriter, r *http.Request) {
423443
return
424444
}
425445
if err != nil {
446+
logger.Error(ctx, "oauth2: login failed", slog.F("user", user.Username), slog.Error(err))
426447
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
427448
Message: "Failed to process OAuth login.",
428449
Detail: err.Error(),
@@ -521,20 +542,23 @@ func (api *API) userOIDC(rw http.ResponseWriter, r *http.Request) {
521542
return
522543
}
523544

545+
logger := api.Logger.Named(userAuthLoggerName)
546+
524547
// "email_verified" is an optional claim that changes the behavior
525548
// of our OIDC handler, so each property must be pulled manually out
526549
// of the claim mapping.
527550
claims := map[string]interface{}{}
528551
err = idToken.Claims(&claims)
529552
if err != nil {
553+
logger.Error(ctx, "oauth2: unable to extract OIDC claims", slog.Error(err))
530554
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
531555
Message: "Failed to extract OIDC claims.",
532556
Detail: err.Error(),
533557
})
534558
return
535559
}
536560

537-
api.Logger.Debug(ctx, "got oidc claims",
561+
logger.Debug(ctx, "got oidc claims",
538562
slog.F("source", "id_token"),
539563
slog.F("claim_fields", claimFields(claims)),
540564
slog.F("blank", blankFields(claims)),
@@ -556,13 +580,14 @@ func (api *API) userOIDC(rw http.ResponseWriter, r *http.Request) {
556580
userInfoClaims := map[string]interface{}{}
557581
err = userInfo.Claims(&userInfoClaims)
558582
if err != nil {
583+
logger.Error(ctx, "oauth2: unable to unmarshal user info claims", slog.Error(err))
559584
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
560585
Message: "Failed to unmarshal user info claims.",
561586
Detail: err.Error(),
562587
})
563588
return
564589
}
565-
api.Logger.Debug(ctx, "got oidc claims",
590+
logger.Debug(ctx, "got oidc claims",
566591
slog.F("source", "userinfo"),
567592
slog.F("claim_fields", claimFields(userInfoClaims)),
568593
slog.F("blank", blankFields(userInfoClaims)),
@@ -573,12 +598,13 @@ func (api *API) userOIDC(rw http.ResponseWriter, r *http.Request) {
573598
claims = mergeClaims(claims, userInfoClaims)
574599

575600
// Log all of the field names after merging.
576-
api.Logger.Debug(ctx, "got oidc claims",
601+
logger.Debug(ctx, "got oidc claims",
577602
slog.F("source", "merged"),
578603
slog.F("claim_fields", claimFields(claims)),
579604
slog.F("blank", blankFields(claims)),
580605
)
581606
} else if !strings.Contains(err.Error(), "user info endpoint is not supported by this provider") {
607+
logger.Error(ctx, "oauth2: unable to obtain user information claims", slog.Error(err))
582608
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
583609
Message: "Failed to obtain user information claims.",
584610
Detail: "The attempt to fetch claims via the UserInfo endpoint failed: " + err.Error(),
@@ -588,7 +614,7 @@ func (api *API) userOIDC(rw http.ResponseWriter, r *http.Request) {
588614
// The OIDC provider does not support the UserInfo endpoint.
589615
// This is not an error, but we should log it as it may mean
590616
// that some claims are missing.
591-
api.Logger.Warn(ctx, "OIDC provider does not support the user info endpoint, ensure that all required claims are present in the id_token")
617+
logger.Warn(ctx, "OIDC provider does not support the user info endpoint, ensure that all required claims are present in the id_token")
592618
}
593619
}
594620

@@ -632,7 +658,7 @@ func (api *API) userOIDC(rw http.ResponseWriter, r *http.Request) {
632658
})
633659
return
634660
}
635-
api.Logger.Warn(ctx, "allowing unverified oidc email %q")
661+
logger.Warn(ctx, "allowing unverified oidc email %q")
636662
}
637663
}
638664

@@ -647,7 +673,7 @@ func (api *API) userOIDC(rw http.ResponseWriter, r *http.Request) {
647673
// Convert the []interface{} we get to a []string.
648674
groupsInterface, ok := groupsRaw.([]interface{})
649675
if ok {
650-
api.Logger.Debug(ctx, "groups returned in oidc claims",
676+
logger.Debug(ctx, "groups returned in oidc claims",
651677
slog.F("len", len(groupsInterface)),
652678
slog.F("groups", groupsInterface),
653679
)
@@ -668,7 +694,7 @@ func (api *API) userOIDC(rw http.ResponseWriter, r *http.Request) {
668694
groups = append(groups, group)
669695
}
670696
} else {
671-
api.Logger.Debug(ctx, "groups field was an unknown type",
697+
logger.Debug(ctx, "groups field was an unknown type",
672698
slog.F("type", fmt.Sprintf("%T", groupsRaw)),
673699
)
674700
}
@@ -678,7 +704,7 @@ func (api *API) userOIDC(rw http.ResponseWriter, r *http.Request) {
678704
// This conditional is purely to warn the user they might have misconfigured their OIDC
679705
// configuration.
680706
if _, groupClaimExists := claims["groups"]; !usingGroups && groupClaimExists {
681-
api.Logger.Debug(ctx, "claim 'groups' was returned, but 'oidc-group-field' is not set, check your coder oidc settings")
707+
logger.Debug(ctx, "claim 'groups' was returned, but 'oidc-group-field' is not set, check your coder oidc settings")
682708
}
683709

684710
// The username is a required property in Coder. We make a best-effort
@@ -719,6 +745,7 @@ func (api *API) userOIDC(rw http.ResponseWriter, r *http.Request) {
719745

720746
user, link, err := findLinkedUser(ctx, api.Database, oidcLinkedID(idToken), email)
721747
if err != nil {
748+
logger.Error(ctx, "oauth2: unable to find linked user", slog.F("email", email), slog.Error(err))
722749
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
723750
Message: "Failed to find linked user.",
724751
Detail: err.Error(),
@@ -754,6 +781,7 @@ func (api *API) userOIDC(rw http.ResponseWriter, r *http.Request) {
754781
return
755782
}
756783
if err != nil {
784+
logger.Error(ctx, "oauth2: login failed", slog.F("user", user.Username), slog.Error(err))
757785
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
758786
Message: "Failed to process OAuth login.",
759787
Detail: err.Error(),

coderd/userauth_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ import (
1818
"golang.org/x/oauth2"
1919
"golang.org/x/xerrors"
2020

21+
"cdr.dev/slog/sloggers/slogtest"
22+
2123
"github.com/coder/coder/coderd"
2224
"github.com/coder/coder/coderd/audit"
2325
"github.com/coder/coder/coderd/coderdtest"
@@ -747,9 +749,11 @@ func TestUserOIDC(t *testing.T) {
747749
config.IgnoreEmailVerified = tc.IgnoreEmailVerified
748750
config.IgnoreUserInfo = tc.IgnoreUserInfo
749751

752+
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
750753
client := coderdtest.New(t, &coderdtest.Options{
751754
Auditor: auditor,
752755
OIDCConfig: config,
756+
Logger: &logger,
753757
})
754758
numLogs := len(auditor.AuditLogs())
755759

coderd/workspacebuilds.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ import (
1414
"golang.org/x/exp/slices"
1515
"golang.org/x/xerrors"
1616

17+
"cdr.dev/slog"
18+
1719
"github.com/coder/coder/coderd/database"
1820
"github.com/coder/coder/coderd/database/db2sdk"
1921
"github.com/coder/coder/coderd/database/dbauthz"
@@ -348,6 +350,10 @@ func (api *API) postWorkspaceBuilds(rw http.ResponseWriter, r *http.Request) {
348350
)
349351
var buildErr wsbuilder.BuildError
350352
if xerrors.As(err, &buildErr) {
353+
if buildErr.Status == http.StatusInternalServerError {
354+
api.Logger.Error(ctx, "workspace build error", slog.Error(buildErr.Wrapped))
355+
}
356+
351357
httpapi.Write(ctx, rw, buildErr.Status, codersdk.Response{
352358
Message: buildErr.Message,
353359
Detail: buildErr.Error(),

coderd/workspaces.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,10 @@ func (api *API) postWorkspacesByOrganization(rw http.ResponseWriter, r *http.Req
454454
}, nil)
455455
var bldErr wsbuilder.BuildError
456456
if xerrors.As(err, &bldErr) {
457+
if bldErr.Status == http.StatusInternalServerError {
458+
api.Logger.Error(ctx, "workspace build error", slog.Error(bldErr.Wrapped))
459+
}
460+
457461
httpapi.Write(ctx, rw, bldErr.Status, codersdk.Response{
458462
Message: bldErr.Message,
459463
Detail: bldErr.Error(),

0 commit comments

Comments
 (0)