Skip to content
This repository has been archived by the owner on Oct 3, 2023. It is now read-only.

Commit

Permalink
Add an 'all' tab to show entire code reference in new tracing quickst…
Browse files Browse the repository at this point in the history
…arts (#486)
  • Loading branch information
hvent90 authored and Emmanuel T Odeke committed Nov 28, 2018
1 parent aad31d9 commit 499a0ee
Show file tree
Hide file tree
Showing 4 changed files with 231 additions and 0 deletions.
71 changes: 71 additions & 0 deletions content/quickstart/go/tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class: "shadowed-image lightbox"
![](/images/go-tracing-zipkin.png)

#### How does it work?
{{% tabs Snippet All %}}
```go
func main() {
// 1. Configure exporter to export traces to Zipkin.
Expand All @@ -53,6 +54,76 @@ func main() {
}
```

```go
package main

import (
"bytes"
"context"
"encoding/binary"
"fmt"
"log"
"time"

"go.opencensus.io/exporter/zipkin"
"go.opencensus.io/trace"

openzipkin "github.com/openzipkin/zipkin-go"
zipkinHTTP "github.com/openzipkin/zipkin-go/reporter/http"
)

func main() {
// 1. Configure exporter to export traces to Zipkin.
localEndpoint, err := openzipkin.NewEndpoint("go-quickstart", "192.168.1.5:5454")
if err != nil {
log.Fatalf("Failed to create the local zipkinEndpoint: %v", err)
}
reporter := zipkinHTTP.NewReporter("http://localhost:9411/api/v2/spans")
ze := zipkin.NewExporter(reporter, localEndpoint)
trace.RegisterExporter(ze)

// 2. Configure 100% sample rate, otherwise, few traces will be sampled.
trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})

// 3. Create a span with the background context, making this the parent span.
// A span must be closed.
ctx, span := trace.StartSpan(context.Background(), "main")
// 5b. Make the span close at the end of this function.
defer span.End()

for i := 0; i < 10; i++ {
doWork(ctx)
}
}

func doWork(ctx context.Context) {
// 4. Start a child span. This will be a child span because we've passed
// the parent span's ctx.
_, span := trace.StartSpan(ctx, "doWork")
// 5a. Make the span close at the end of this function.
defer span.End()

fmt.Println("doing busy work")
time.Sleep(80 * time.Millisecond)
buf := bytes.NewBuffer([]byte{0xFF, 0x00, 0x00, 0x00})
num, err := binary.ReadVarint(buf)
if err != nil {
// 6. Set status upon error
span.SetStatus(trace.Status{
Code: trace.StatusCodeUnknown,
Message: err.Error(),
})
}

// 7. Annotate our span to capture metadata about our operation
span.Annotate([]trace.Attribute{
trace.Int64Attribute("bytes to int", num),
}, "Invoking doWork")
time.Sleep(20 * time.Millisecond)
}
```
{{% /tabs %}}

#### Configure Exporter
OpenCensus can export traces to different distributed tracing stores (such as Zipkin, Jeager, Stackdriver Trace). In (1), we configure OpenCensus to export to Zipkin, which is listening on `localhost` port `9411`, and all of the traces from this program will be associated with a service name `go-quickstart`.
```go
Expand Down
74 changes: 74 additions & 0 deletions content/quickstart/java/tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ class: "shadowed-image lightbox"

#### How does it work?

{{% tabs Snippet All %}}
```java
public static void main(String[] args) {
// 1. Configure exporter to export traces to Zipkin.
Expand Down Expand Up @@ -81,6 +82,79 @@ public static void main(String[] args) {
}
```

```java
package com.example;

import java.util.HashMap;
import java.util.Map;

import io.opencensus.trace.AttributeValue;
import io.opencensus.common.Scope;
import io.opencensus.trace.Span;
import io.opencensus.trace.Status;
import io.opencensus.exporter.trace.zipkin.ZipkinTraceExporter;
import io.opencensus.trace.Tracer;
import io.opencensus.trace.Tracing;
import io.opencensus.trace.config.TraceConfig;
import io.opencensus.trace.config.TraceParams;
import io.opencensus.trace.samplers.Samplers;

public class TracingToZipkin {
public static void main(String[] args) {
// 1. Configure exporter to export traces to Zipkin.
ZipkinTraceExporter.createAndRegister("http://localhost:9411/api/v2/spans", "tracing-to-zipkin-service");

// 2. Configure 100% sample rate, otherwise, few traces will be sampled.
TraceConfig traceConfig = Tracing.getTraceConfig();
TraceParams activeTraceParams = traceConfig.getActiveTraceParams();
traceConfig.updateActiveTraceParams(activeTraceParams.toBuilder().setSampler(Samplers.alwaysSample()).build());

// 3. Get the global singleton Tracer object.
Tracer tracer = Tracing.getTracer();

// 4. Create a scoped span, a scoped span will automatically end when closed.
// It implements AutoClosable, so it'll be closed when the try block ends.
try (Scope scope = tracer.spanBuilder("main").startScopedSpan()) {
System.out.println("About to do some busy work...");
for (int i = 0; i < 10; i++) {
doWork(i);
}
}

// 5. Gracefully shutdown the exporter, so that it'll flush queued traces to Zipkin.
Tracing.getExportComponent().shutdown();
}

private static void doWork(int i) {
// 6. Get the global singleton Tracer object.
Tracer tracer = Tracing.getTracer();

// 7. Start another span. If antoher span was already started, it'll use that span as the parent span.
// In this example, the main method already started a span, so that'll be the parent span, and this will be
// a child span.
try (Scope scope = tracer.spanBuilder("doWork").startScopedSpan()) {
// Simulate some work.
Span span = tracer.getCurrentSpan();

try {
System.out.println("doing busy work");
Thread.sleep(100L);
}
catch (InterruptedException e) {
// 6. Set status upon error
span.setStatus(Status.INTERNAL.withDescription(e.toString()));
}

// 7. Annotate our span to capture metadata about our operation
Map<String, AttributeValue> attributes = new HashMap<String, AttributeValue>();
attributes.put("use", AttributeValue.stringAttributeValue("demo"));
span.addAnnotation("Invoking doWork", attributes);
}
}
}
```
{{% /tabs %}}

#### Configure Exporter

OpenCensus can export traces to different distributed tracing stores \(such as Zipkin, Jeager, Stackdriver Trace\). In \(1\), we configure OpenCensus to export to Zipkin, which is listening on `localhost` port `9411`, and all of the traces from this program will be associated with a service name `tracing-to-zipkin-service`.
Expand Down
47 changes: 47 additions & 0 deletions content/quickstart/nodejs/tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ aliases: [/quickstart/node.js/tracing]
![](/images/node-tracing-zipkin.png)

#### How does it work?
{{% tabs Snippet All %}}
```js
// 1. Get the global singleton Tracer object
// 2. Configure 100% sample rate, otherwise, few traces will be sampled.
Expand All @@ -55,6 +56,52 @@ function main() {
}
```

```js
const tracing = require('@opencensus/nodejs');
const zipkin = require('@opencensus/exporter-zipkin');
const stdin = process.openStdin();

// 1. Get the global singleton Tracer object
// 2. Configure 100% sample rate, otherwise, few traces will be sampled.
const tracer = tracing.start({samplingRate: 1}).tracer;

// 3. Configure exporter to export traces to Zipkin.
tracer.registerSpanEventListener(new zipkin.ZipkinTraceExporter({
url: 'http://localhost:9411/api/v2/spans',
serviceName: 'node.js-quickstart'
}));

function main() {
// 4. Create a span. A span must be closed.
tracer.startRootSpan({name: 'main'}, rootSpan => {
for (let i = 0; i < 10; i++) {
doWork();
}

rootSpan.end();
});
}

function doWork() {
// 5. Start another span. In this example, the main method already started a span,
// so that'll be the parent span, and this will be a child span.
const span = tracer.startChildSpan('doWork');
span.start();

console.log('doing busy work');
for (let i = 0; i <= 40000000; i++) {} // short delay

// 6. Annotate our span to capture metadata about our operation
span.addAnnotation('invoking doWork')
for (let i = 0; i <= 20000000; i++) {} // short delay

span.end();
}

main();
```
{{% /tabs %}}

#### Using the Tracer
To start a trace, you first need to get a reference to the `Tracer` (3). It can be retrieved as a global singleton.
```js
Expand Down
39 changes: 39 additions & 0 deletions content/quickstart/python/tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,35 @@ class: "shadowed-image lightbox"
![](/images/python-tracing-zipkin.png)

#### How does it work?
{{% tabs Snippet All %}}
```py
# 1a. Setup the exporter
ze = ZipkinExporter(service_name="python-quickstart",
host_name='localhost',
port=9411,
endpoint='/api/v2/spans')
# 1b. Set the tracer to use the exporter
# 2. Configure 100% sample rate, otherwise, few traces will be sampled.
# 3. Get the global singleton Tracer object
tracer = Tracer(exporter=ze, sampler=always_on.AlwaysOnSampler())

def main():
# 4. Create a scoped span. The span will close at the end of the block.
with tracer.span(name="main") as span:
for i in range(0, 10):
doWork()
```

```py
#!/usr/bin/env python

import os
from datetime import datetime
import time
import sys

from opencensus.trace.tracer import Tracer
from opencensus.trace import time_event as time_event_module
from opencensus.trace.exporters.zipkin_exporter import ZipkinExporter
from opencensus.trace.samplers import always_on

Expand All @@ -54,7 +75,25 @@ def main():
with tracer.span(name="main") as span:
for i in range(0, 10):
doWork()

def doWork():
# 5. Start another span. Because this is within the scope of the "main" span,
# this will automatically be a child span.
with tracer.span(name="doWork") as span:
print("doing busy work")
try:
time.sleep(0.1)
except:
# 6. Set status upon error
span.status = Status(5, "Error occurred")

# 7. Annotate our span to capture metadata about our operation
span.add_annotation("invoking doWork")

if __name__ == "__main__":
main()
```
{{% /tabs %}}

#### Configure Exporter
OpenCensus can export traces to different distributed tracing stores (such as Zipkin, Jeager, Stackdriver Trace). In (1), we configure OpenCensus to export to Zipkin, which is listening on `localhost` port `9411`, and all of the traces from this program will be associated with a service name `python-quickstart`.
Expand Down

0 comments on commit 499a0ee

Please sign in to comment.