Skip to content

Commit 0e397ed

Browse files
committed
initial implementation of RequestLoggerContext and example usage in ProvisionerJobs logs
1 parent 0b2b643 commit 0e397ed

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

coderd/httpmw/logger.go

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,14 @@ func Logger(log slog.Logger) func(next http.Handler) http.Handler {
3535
slog.F("start", start),
3636
)
3737

38-
next.ServeHTTP(sw, r)
38+
logContext := &RequestLoggerContext{}
39+
defer func() {
40+
logContext.WriteLog(r.Context(), "", sw.Status)
41+
}()
42+
43+
ctx := context.WithValue(r.Context(), logContextKey{}, logContext)
44+
45+
next.ServeHTTP(sw, r.WithContext(ctx))
3946

4047
end := time.Now()
4148

@@ -74,3 +81,37 @@ func Logger(log slog.Logger) func(next http.Handler) http.Handler {
7481
})
7582
}
7683
}
84+
85+
type RequestLoggerContext struct {
86+
Fields map[string]any
87+
88+
log *slog.Logger
89+
written bool
90+
}
91+
92+
func (c *RequestLoggerContext) WriteLog(ctx context.Context, msg string, status int) {
93+
if c.written {
94+
return
95+
}
96+
c.written = true
97+
// append extra fields to the logger
98+
for k, v := range c.Fields {
99+
c.log.With(slog.F(k, v))
100+
}
101+
102+
if status >= http.StatusInternalServerError {
103+
c.log.Error(ctx, msg)
104+
} else {
105+
c.log.Debug(ctx, msg)
106+
}
107+
}
108+
109+
type logContextKey struct{}
110+
111+
func FromContext(ctx context.Context) *RequestLoggerContext {
112+
val := ctx.Value(logContextKey{})
113+
if logCtx, ok := val.(*RequestLoggerContext); ok {
114+
return logCtx
115+
}
116+
return nil
117+
}

coderd/provisionerjobs.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,10 @@ func (f *logFollower) follow() {
554554
return
555555
}
556556

557+
// write the initial logs to the connection
558+
httpmw.FromContext(f.ctx).WriteLog(
559+
f.ctx, "ProvisionerJobs log follower WS connection established", http.StatusAccepted)
560+
557561
// no need to wait if the job is done
558562
if f.complete {
559563
return

0 commit comments

Comments
 (0)