Created
November 1, 2018 05:14
-
-
Save castaneai/8ec512239839d6ffcc2469a276fa8598 to your computer and use it in GitHub Desktop.
gae/go + spanner + opencensus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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{})) | |
} |
このあたりがないと、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
ochttp.Handler
を入れないと request span と spanner通信の span が別々になってしまい、非常に見づらいのでochttp.Handler
は必要。