Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions cloudrequestlog/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"runtime"
"time"

"go.einride.tech/cloudrunner/cloudslog"
"go.einride.tech/cloudrunner/cloudstream"
ltype "google.golang.org/genproto/googleapis/logging/type"
"google.golang.org/grpc"
Expand All @@ -32,6 +33,7 @@ func (l *Middleware) GRPCUnaryServerInterceptor(
) (interface{}, error) {
startTime := time.Now()
ctx = WithAdditionalFields(ctx)
ctx = cloudslog.WithHTTPRequest(ctx, &ltype.HttpRequest{Protocol: "gRPC"})
// Clone request to ensure not using a mutated one later
requestClone := proto.Clone(request.(proto.Message))
response, err := handler(ctx, request)
Expand Down Expand Up @@ -84,6 +86,7 @@ func (l *Middleware) GRPCStreamServerInterceptor(
) error {
startTime := time.Now()
ctx := WithAdditionalFields(ss.Context())
ctx = cloudslog.WithHTTPRequest(ctx, &ltype.HttpRequest{Protocol: "gRPC"})
ss = cloudstream.NewContextualServerStream(ctx, ss)
err := handler(srv, ss)
responseStatus := status.Convert(err)
Expand Down Expand Up @@ -190,6 +193,17 @@ func (l *Middleware) HTTPServer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
ctx := WithAdditionalFields(r.Context())
httpReq := &ltype.HttpRequest{
RequestMethod: r.Method,
UserAgent: r.UserAgent(),
RemoteIp: r.RemoteAddr,
Referer: r.Referer(),
Protocol: r.Proto,
}
if r.URL != nil {
httpReq.RequestUrl = r.URL.String()
}
ctx = cloudslog.WithHTTPRequest(ctx, httpReq)
r = r.WithContext(ctx)
responseWriter := &httpResponseWriter{ResponseWriter: w}
next.ServeHTTP(responseWriter, r)
Expand Down
18 changes: 12 additions & 6 deletions cloudslog/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,17 +85,23 @@ func (t *handler) Handle(ctx context.Context, record slog.Record) error {
}
}

// Build context group with optional httpRequest and reportLocation.
var contextAttrs []any
if httpRequest := httpRequestFromContext(ctx); httpRequest != nil {
contextAttrs = append(contextAttrs, slog.Any("httpRequest", httpRequest))
}
if record.PC != 0 {
fs := runtime.CallersFrames([]uintptr{record.PC})
f, _ := fs.Next()
record.AddAttrs(slog.Group("context",
slog.Group("reportLocation",
slog.String("filePath", f.File),
slog.Int("lineNumber", f.Line),
slog.String("functionName", f.Function),
),
contextAttrs = append(contextAttrs, slog.Group("reportLocation",
slog.String("filePath", f.File),
slog.Int("lineNumber", f.Line),
slog.String("functionName", f.Function),
))
}
if len(contextAttrs) > 0 {
record.AddAttrs(slog.Group("context", contextAttrs...))
}
}
record.AddAttrs(attributesFromContext(ctx)...)
return t.Handler.Handle(ctx, record)
Expand Down
21 changes: 21 additions & 0 deletions cloudslog/httprequest_context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package cloudslog

import (
"context"

ltype "google.golang.org/genproto/googleapis/logging/type"
)

type httpRequestContextKey struct{}

// WithHTTPRequest stores an [ltype.HttpRequest] on the context for use in error reporting.
// This should be called by request middleware before handling the request, so that
// error reports logged during request handling can include HTTP request context.
func WithHTTPRequest(parent context.Context, req *ltype.HttpRequest) context.Context {
return context.WithValue(parent, httpRequestContextKey{}, req)
}

func httpRequestFromContext(ctx context.Context) *ltype.HttpRequest {
req, _ := ctx.Value(httpRequestContextKey{}).(*ltype.HttpRequest)
return req
}
49 changes: 49 additions & 0 deletions cloudslog/httprequest_context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package cloudslog

import (
"context"
"log/slog"
"strings"
"testing"

ltype "google.golang.org/genproto/googleapis/logging/type"
"gotest.tools/v3/assert"
)

func TestHandler_httpRequestFromContext(t *testing.T) {
t.Run("included in error report context", func(t *testing.T) {
var b strings.Builder
logger := slog.New(newHandler(&b, LoggerConfig{ReportErrors: true}))
ctx := WithHTTPRequest(context.Background(), &ltype.HttpRequest{
RequestMethod: "GET",
RequestUrl: "/test/path",
UserAgent: "test-agent",
})
logger.ErrorContext(ctx, "something went wrong")
got := b.String()
assert.Assert(t, strings.Contains(got, `"requestMethod":"GET"`), got)
assert.Assert(t, strings.Contains(got, `"requestUrl":"/test/path"`), got)
assert.Assert(t, strings.Contains(got, `"userAgent":"test-agent"`), got)
})

t.Run("not included when no httpRequest on context", func(t *testing.T) {
var b strings.Builder
logger := slog.New(newHandler(&b, LoggerConfig{ReportErrors: true}))
logger.ErrorContext(context.Background(), "something went wrong")
got := b.String()
assert.Assert(t, !strings.Contains(got, `"httpRequest"`), got)
})

t.Run("not included for non-error levels", func(t *testing.T) {
var b strings.Builder
logger := slog.New(newHandler(&b, LoggerConfig{ReportErrors: true}))
ctx := WithHTTPRequest(context.Background(), &ltype.HttpRequest{
RequestMethod: "GET",
RequestUrl: "/test/path",
})
logger.InfoContext(ctx, "just info")
got := b.String()
// httpRequest should not appear in the context group for non-error logs.
assert.Assert(t, !strings.Contains(got, `"httpRequest"`), got)
})
}