You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

78 lines
2.3 KiB

  1. // Copyright 2018, OpenCensus Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "fmt"
  17. "log"
  18. "net/http"
  19. "time"
  20. "go.opencensus.io/zpages"
  21. "go.opencensus.io/examples/exporter"
  22. "go.opencensus.io/plugin/ochttp"
  23. "go.opencensus.io/stats/view"
  24. "go.opencensus.io/trace"
  25. )
  26. func main() {
  27. // Start z-Pages server.
  28. go func() {
  29. mux := http.NewServeMux()
  30. zpages.Handle(mux, "/debug")
  31. log.Fatal(http.ListenAndServe("127.0.0.1:8081", mux))
  32. }()
  33. // Register stats and trace exporters to export the collected data.
  34. exporter := &exporter.PrintExporter{}
  35. view.RegisterExporter(exporter)
  36. trace.RegisterExporter(exporter)
  37. // Always trace for this demo. In a production application, you should
  38. // configure this to a trace.ProbabilitySampler set at the desired
  39. // probability.
  40. trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})
  41. // Report stats at every second.
  42. view.SetReportingPeriod(1 * time.Second)
  43. client := &http.Client{Transport: &ochttp.Transport{}}
  44. http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
  45. fmt.Fprintf(w, "hello world")
  46. // Provide an example of how spans can be annotated with metadata
  47. _, span := trace.StartSpan(req.Context(), "child")
  48. defer span.End()
  49. span.Annotate([]trace.Attribute{trace.StringAttribute("key", "value")}, "something happened")
  50. span.AddAttributes(trace.StringAttribute("hello", "world"))
  51. time.Sleep(time.Millisecond * 125)
  52. r, _ := http.NewRequest("GET", "https://example.com", nil)
  53. // Propagate the trace header info in the outgoing requests.
  54. r = r.WithContext(req.Context())
  55. resp, err := client.Do(r)
  56. if err != nil {
  57. log.Println(err)
  58. } else {
  59. // TODO: handle response
  60. resp.Body.Close()
  61. }
  62. })
  63. log.Fatal(http.ListenAndServe(":50030", &ochttp.Handler{}))
  64. }