Skip to content

Commit 8c4afb7

Browse files
committed
feat: add SetContext for CloudFunctions
1 parent 055b599 commit 8c4afb7

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

middleware.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,42 @@ func RequestLoggingWithEcho(config *Config) echo.MiddlewareFunc {
9090
}
9191
}
9292

93+
// SetContext for CloudFunctions
94+
func SetContext(config *Config, w http.ResponseWriter, r *http.Request) {
95+
before := time.Now()
96+
97+
traceId := getTraceId(r)
98+
if traceId == "" {
99+
// there is no span yet, so create one
100+
var ctx context.Context
101+
traceId, ctx = generateTraceId(r)
102+
r = r.WithContext(ctx)
103+
}
104+
105+
traces := fmt.Sprintf("projects/%s/traces/%s", config.ProjectId, traceId)
106+
107+
contextLogger := &ContextLogger{
108+
out: config.ContextLogOut,
109+
Trace: traces,
110+
Severity: config.Severity,
111+
AdditionalData: config.AdditionalData,
112+
loggedSeverity: make([]Severity, 0, 10),
113+
}
114+
ctx := context.WithValue(r.Context(), contextLoggerKey, contextLogger)
115+
r = r.WithContext(ctx)
116+
117+
wrw := &wrappedResponseWriter{ResponseWriter: w}
118+
defer func() {
119+
// logging
120+
elapsed := time.Since(before)
121+
maxSeverity := contextLogger.maxSeverity()
122+
err := writeRequestLog(r, config, wrw.status, wrw.responseSize, elapsed, traces, maxSeverity)
123+
if err != nil {
124+
_, _ = fmt.Fprintln(os.Stderr, err.Error())
125+
}
126+
}()
127+
}
128+
93129
func getTraceId(r *http.Request) string {
94130
span := trace.FromContext(r.Context())
95131
if span != nil {

0 commit comments

Comments
 (0)