Last active
June 27, 2018 02:50
-
-
Save semistrict/7e4a1bc8fef51bf4da783d9de984bfd0 to your computer and use it in GitHub Desktop.
How to avoid sending logging spans to Stackdriver with 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 ( | |
"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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this work for you? I'm still seeing the logger trace with this code.