Skip to content

Instantly share code, notes, and snippets.

@semistrict
Last active June 27, 2018 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save semistrict/7e4a1bc8fef51bf4da783d9de984bfd0 to your computer and use it in GitHub Desktop.
Save semistrict/7e4a1bc8fef51bf4da783d9de984bfd0 to your computer and use it in GitHub Desktop.
How to avoid sending logging spans to Stackdriver with OpenCensus
package main
import (
"context"
"log"
"time"
"cloud.google.com/go/logging"
"contrib.go.opencensus.io/exporter/stackdriver"
"go.opencensus.io/trace"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
)
const (
gcpCredentials = `your-json-credentials-here`
)
func check(err error) {
if err != nil {
log.Fatalln(err)
}
}
func main() {
ctx := context.Background()
credentials, err := google.CredentialsFromJSON(ctx, []byte(gcpCredentials),
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/trace.append",
"https://www.googleapis.com/auth/trace.readonly",
logging.WriteScope,
)
check(err)
exporter, err := stackdriver.NewExporter(stackdriver.Options{
ProjectID: credentials.ProjectID,
TraceClientOptions: []option.ClientOption{
option.WithCredentials(credentials),
},
})
check(err)
defer exporter.Flush()
trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})
trace.RegisterExporter(exporter)
logCtx, span := trace.StartSpan(ctx, "this span will not be exported", trace.WithSampler(trace.NeverSample()))
defer span.End()
client, err := logging.NewClient(logCtx, credentials.ProjectID, option.WithCredentials(credentials))
check(err)
defer client.Close()
logger := client.Logger("example", logging.EntryCountThreshold(1))
example(ctx, logger)
time.Sleep(2 * time.Second)
}
// example should generate 1 trace, not two. currently, it generates two traces.
func example(ctx context.Context, logger *logging.Logger) error {
ctx, span := trace.StartSpan(ctx, "example")
defer span.End()
time.Sleep(125 * time.Millisecond)
logger.Log(logging.Entry{Payload: "hello example"})
time.Sleep(125 * time.Millisecond)
return nil
}
@savaki
Copy link

savaki commented Jun 27, 2018

Does this work for you? I'm still seeing the logger trace with this code.

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