Skip to content

Instantly share code, notes, and snippets.

@sbuss
Last active August 15, 2019 20:23
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sbuss/d47aea3751a1fbb477f8937d992bc1e0 to your computer and use it in GitHub Desktop.
Save sbuss/d47aea3751a1fbb477f8937d992bc1e0 to your computer and use it in GitHub Desktop.
Stackdriver logging with request grouping for App Engine Go 1.11
// Sample logging-quickstart writes a log entry to Stackdriver Logging.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"strings"
// Imports the Stackdriver Logging client package.
"cloud.google.com/go/logging"
"google.golang.org/genproto/googleapis/api/monitoredres"
)
const logName = "app_logs"
var (
projectID string
requestCount int
monRes *monitoredres.MonitoredResource
)
func main() {
projectID = os.Getenv("GOOGLE_CLOUD_PROJECT")
monRes = &monitoredres.MonitoredResource{
Labels: map[string]string{
"module_id": os.Getenv("GAE_SERVICE"),
"project_id": projectID,
"version_id": os.Getenv("GAE_VERSION"),
},
Type: "gae_app",
}
http.HandleFunc("/", index)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
func traceID(r *http.Request) string {
return fmt.Sprintf("projects/%s/traces/%s", projectID, strings.Split(r.Header.Get("X-Cloud-Trace-Context"), "/")[0])
}
func newClient(ctx context.Context) *logging.Client {
client, err := logging.NewClient(ctx, fmt.Sprintf("projects/%s", projectID))
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
return client
}
func index(w http.ResponseWriter, r *http.Request) {
defer func() {
requestCount += 1
}()
client := newClient(r.Context())
defer client.Close()
lg := client.Logger(logName)
trace := traceID(r)
t := fmt.Sprintf("[request #%d] First entry", requestCount)
lg.Log(logging.Entry{
Payload: t,
Trace: trace,
Resource: monRes,
})
fmt.Fprintf(w, "Logged: %v\n", t)
log.Printf("Logged: %v\n", t)
t = fmt.Sprintf("[request #%d] A second entry here!", requestCount)
lg.Log(logging.Entry{
Payload: t,
Trace: trace,
Resource: monRes,
})
fmt.Fprintf(w, "Logged: %v\n", t)
log.Printf("Logged: %v\n", t)
}
@odeke-em
Copy link

I believe that after googleapis/google-cloud-go@392bd16 we now have proper trace, span and isSampled extraction, they no longer need to manually extract traceID and can just do

lg.Log(logging.Entry{
    Request: r,
    Resource: monRes,
    Payload: t,
})

for proper trace and log correlation. They'll just need to update to at least google-cloud-go v0.42.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment