Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add structured log writer #246

Merged

Conversation

garethgeorge
Copy link
Contributor

Background

When using a standard go logger e.g. "log" package's log.Default() we don't get a "spanId" / "trace" in the logs generated:

// HTTP is a simple HTTP function that writes the request body to the response body.
func HTTPNoLog(w http.ResponseWriter, r *http.Request) {
	log.Default().Println("handling HTTP request without span / trace ID logging")
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	if err := ioutil.WriteFile(outputFile, body, 0644); err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
}

This can make it hard to associate logs printed with the invocation generating them e.g.

image

No span ID / trace ID is captured for logs generated by default when using concurrency.

Proposal

Include a funcframework package utility for creating io.Writers that produce structured logs and that are compatible with common logging frameworks (e.g. "log" by default.


// HTTP is a simple HTTP function that writes the request body to the response body.
func HTTP(w http.ResponseWriter, r *http.Request) {
	l := log.New(funcframework.LogWriter(r.Context()), "", log.Lshortfile)
	l.Println("handling HTTP request")
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	if err := ioutil.WriteFile(outputFile, body, 0644); err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
}
image

Or, alternatively a CX can extract the trace ID and other logging IDs from the request context if needed using the utilities:

funcframework.ExecutionIDFromContext(ctx context.Context)
funcframework.TraceIDFromContext(ctx context.Context)
funcframework.SpanIDFromContext(ctx context.Context)

@garethgeorge garethgeorge requested a review from jrmfg June 20, 2024 21:19
@garethgeorge garethgeorge merged commit b8c2a57 into GoogleCloudPlatform:main Jul 1, 2024
33 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants