Skip to content

Instantly share code, notes, and snippets.

@castaneai
Created Nov 1, 2018
Embed
What would you like to do?
gae/go + spanner + opencensus
package main
import (
"cloud.google.com/go/spanner"
"context"
"contrib.go.opencensus.io/exporter/stackdriver"
"fmt"
"go.opencensus.io/plugin/ochttp"
"go.opencensus.io/trace"
"log"
"net/http"
"os"
"time"
)
func main() {
projectID, ok := os.LookupEnv("SPANNER_PROJECT_ID")
if !ok {
log.Fatalf("env not set: SPANNER_PROJECT_ID")
}
instanceID, ok := os.LookupEnv("SPANNER_INSTANCE_ID")
if !ok {
log.Fatalf("env not set: SPANNER_INSTANCE_ID")
}
databaseID, ok := os.LookupEnv("SPANNER_DATABASE_ID")
if !ok {
log.Fatalf("env not set: SPANNER_DATABASE_ID")
}
// Create and register a OpenCensus Stackdriver Trace exporter.
exporter, err := stackdriver.NewExporter(stackdriver.Options{ProjectID: projectID})
if err != nil {
log.Fatal(err)
}
trace.RegisterExporter(exporter)
trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})
ctx := context.Background()
dsn := fmt.Sprintf("projects/%s/instances/%s/databases/%s", projectID, instanceID, databaseID)
client, err := spanner.NewClient(ctx, dsn)
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
stmt := spanner.NewStatement("SELECT 1")
if err := client.Single().Query(r.Context(), stmt).Do(func(row *spanner.Row) error {
return nil
}); err != nil {
fmt.Fprintf(w, "[err] %+v", err)
}
fmt.Fprintf(w, "Query time: %s\n", time.Since(start))
})
port := os.Getenv("PORT")
if port == "" {
port = "8090"
log.Printf("Defaulting to port %s", port)
}
log.Printf("Listening on port %s", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), &ochttp.Handler{}))
}
@castaneai
Copy link
Author

castaneai commented Nov 1, 2018

ochttp.Handler を入れないと request span と spanner通信の span が別々になってしまい、非常に見づらいので ochttp.Handler は必要。

@castaneai
Copy link
Author

castaneai commented Nov 1, 2018

このあたりがないと、ochttp.Handler や spanner 独自の span が何も出力されなくなる。
逆に、これがなくても appengine 標準のリクエスト全体の時間だけが出る span は出力されていた。
appengine は裏側で別途 exporter を設定しているのだろうか。

	// Create and register a OpenCensus Stackdriver Trace exporter.
	exporter, err := stackdriver.NewExporter(stackdriver.Options{ProjectID: projectID})
	if err != nil {
		log.Fatal(err)
	}
	trace.RegisterExporter(exporter)

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