项目作者: aws

项目描述 :
AWS X-Ray SDK for the Go programming language.
高级语言: Go
项目地址: git://github.com/aws/aws-xray-sdk-go.git
创建时间: 2017-07-19T19:24:10Z
项目社区:https://github.com/aws/aws-xray-sdk-go

开源协议:Apache License 2.0

下载


Test
Go Report Card

:mega: OpenTelemetry Go with AWS X-Ray

AWS X-Ray supports using OpenTelemetry Go and the AWS Distro for OpenTelemetry (ADOT) Collector to instrument your application and send trace data to X-Ray. The OpenTelemetry SDKs are an industry-wide standard for tracing instrumentation. They provide more instrumentations and have a larger community for support, but may not have complete feature parity with the X-Ray SDKs. See choosing between the ADOT and X-Ray SDKs for more help with choosing between the two.

If you want additional features when tracing your Go applications, please open an issue on the OpenTelemetry Go Instrumentation repository.

AWS X-Ray SDK for Go

Screenshot of the AWS X-Ray console

Installing into GOPATH

The AWS X-Ray SDK for Go is compatible with Go 1.23 and above.

Install the SDK using the following command (The SDK’s non-testing dependencies will be installed):
Use go get to retrieve the SDK to add it to your GOPATH workspace:

  1. go get github.com/aws/aws-xray-sdk-go/v2

To update the SDK, use go get -u to retrieve the latest version of the SDK.

  1. go get -u github.com/aws/aws-xray-sdk-go/v2

If you also want to install SDK’s testing dependencies. They can be installed using:

  1. go get -u -t github.com/aws/aws-xray-sdk-go/v2/...

Installing using Go Modules

The latest version of the SDK is the recommended version.

If you are using Go 1.11 and above, you can install the SDK using Go Modules (in project’s go.mod), like so:

  1. go get github.com/aws/aws-xray-sdk-go/v2

To get a different specific release version of the SDK use @<tag> in your go get command. Also, to get the rc version use this command with the specific version.

  1. go get github.com/aws/aws-xray-sdk-go@v1.0.0

Getting Help

Please use these community resources for getting help. We use the GitHub issues for tracking bugs and feature requests.

Opening Issues

If you encounter a bug with the AWS X-Ray SDK for Go we would like to hear about it. Search the existing issues and see if others are also experiencing the issue before opening a new issue. Please include the version of AWS X-Ray SDK for Go, AWS SDK for Go, Go language, and OS you’re using. Please also include repro case when appropriate.

The GitHub issues are intended for bug reports and feature requests. For help and questions regarding the use of the AWS X-Ray SDK for Go please make use of the resources listed in the Getting Help section. Keeping the list of open issues lean will help us respond in a timely manner.

Documentation

The developer guide provides in-depth guidance on using the AWS X-Ray service and the AWS X-Ray SDK for Go.

See aws-xray-sdk-go-sample for a sample application that provides example of tracing SQL queries, incoming and outgoing request. Follow README instructions in that repository to get started with sample application.

Quick Start

Configuration

  1. import "github.com/aws/aws-xray-sdk-go/v2/xray"
  2. func init() {
  3. xray.Configure(xray.Config{
  4. DaemonAddr: "127.0.0.1:2000", // default
  5. ServiceVersion: "1.2.3",
  6. })
  7. }

Logger

xray uses an interface for its logger:

  1. type Logger interface {
  2. Log(level LogLevel, msg fmt.Stringer)
  3. }
  4. const (
  5. LogLevelDebug LogLevel = iota + 1
  6. LogLevelInfo
  7. LogLevelWarn
  8. LogLevelError
  9. )

The default logger logs to stdout at “info” and above. To change the logger, call xray.SetLogger(myLogger). There is a default logger implementation that writes to an io.Writer from a specified minimum log level. For example, to log to stderr at “error” and above:

  1. xray.SetLogger(xraylog.NewDefaultLogger(os.Stderr, xraylog.LogLevelError))

Note that the xray.Config{} fields LogLevel and LogFormat are deprecated starting from version 1.0.0-rc.10 and no longer have any effect.

Plugins

Plugins can be loaded conditionally at runtime. For this purpose, plugins under “github.com/aws/aws-xray-sdk-go/v2/awsplugins/“ have an explicit Init() function. Customer must call this method to load the plugin:

  1. import (
  2. "os"
  3. "github.com/aws/aws-xray-sdk-go/v2/awsplugins/ec2"
  4. "github.com/aws/aws-xray-sdk-go/v2/xray"
  5. )
  6. func init() {
  7. // conditionally load plugin
  8. if os.Getenv("ENVIRONMENT") == "production" {
  9. ec2.Init()
  10. }
  11. xray.Configure(xray.Config{
  12. ServiceVersion: "1.2.3",
  13. })
  14. }

Start a custom segment/subsegment
Note that customers using xray.BeginSegment API directly will only be able to evaluate sampling rules based on service name.

  1. // Start a segment
  2. ctx, seg := xray.BeginSegment(context.Background(), "service-name")
  3. // Start a subsegment
  4. subCtx, subSeg := xray.BeginSubsegment(ctx, "subsegment-name")
  5. // ...
  6. // Add metadata or annotation here if necessary
  7. // ...
  8. subSeg.Close(nil)
  9. // Close the segment
  10. seg.Close(nil)

Generate no-op trace and segment id

X-Ray Go SDK will by default generate no-op trace and segment id for unsampled requests and secure random trace and entity id for sampled requests. If customer wants to enable generating secure random trace and entity id for all the (sampled/unsampled) requests (this is applicable for trace id injection into logs use case) then they achieve that by setting AWS_XRAY_NOOP_ID environment variable as False.

Disabling XRay Tracing

XRay tracing can be disabled by setting up environment variable AWS_XRAY_SDK_DISABLED . Disabling XRay can be useful for specific use case like if customer wants to stop tracing in their test environment they can do so just by setting up the environment variable.

  1. // Set environment variable TRUE to disable XRay
  2. os.Setenv("AWS_XRAY_SDK_DISABLED", "TRUE")

Capture

  1. func criticalSection(ctx context.Context) {
  2. // This example traces a critical code path using a custom subsegment
  3. xray.Capture(ctx, "MyService.criticalSection", func(ctx1 context.Context) error {
  4. var err error
  5. section.Lock()
  6. result := someLockedResource.Go()
  7. section.Unlock()
  8. xray.AddMetadata(ctx1, "ResourceResult", result)
  9. })
  10. }

HTTP Handler

  1. func main() {
  2. http.Handle("/", xray.Handler(xray.NewFixedSegmentNamer("myApp"), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  3. w.Write([]byte("Hello!"))
  4. })))
  5. http.ListenAndServe(":8000", nil)
  6. }

HTTP Client

  1. func getExample(ctx context.Context) ([]byte, error) {
  2. resp, err := ctxhttp.Get(ctx, xray.Client(nil), "https://aws.amazon.com/")
  3. if err != nil {
  4. return nil, err
  5. }
  6. return ioutil.ReadAll(resp.Body)
  7. }

AWS SDK Instrumentation

[!WARNING]
Support for AWS SDK V1 Instrumentation has been removed in v2.0.0 of the AWS X-Ray SDK for Go

  1. func main() {
  2. // Create a segment
  3. ctx, root := xray.BeginSegment(context.TODO(), "AWSSDKV1_Dynamodb")
  4. defer root.Close(nil)
  5. sess := session.Must(session.NewSession())
  6. dynamo := dynamodb.New(sess)
  7. // Instrumenting with AWS SDK v1:
  8. // Wrap the client object with `xray.AWS()`
  9. xray.AWS(dynamo.Client)
  10. // Use the `-WithContext` version of the `ListTables` method
  11. output := dynamo.ListTablesWithContext(ctx, &dynamodb.ListTablesInput{})
  12. doSomething(output)
  13. }

Segment creation is not necessary in an AWS Lambda function, where the segment is created automatically

AWS SDK V2 Instrumentation

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "github.com/aws/aws-sdk-go-v2/aws"
  6. "github.com/aws/aws-sdk-go-v2/config"
  7. "github.com/aws/aws-sdk-go-v2/service/dynamodb"
  8. "github.com/aws/aws-xray-sdk-go/v2/instrumentation/awsv2"
  9. "github.com/aws/aws-xray-sdk-go/v2/xray"
  10. )
  11. func main() {
  12. // Create a segment
  13. ctx, root := xray.BeginSegment(context.TODO(), "AWSSDKV2_Dynamodb")
  14. defer root.Close(nil)
  15. cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-west-2"))
  16. if err != nil {
  17. log.Fatalf("unable to load SDK config, %v", err)
  18. }
  19. // Instrumenting AWS SDK v2
  20. awsv2.AWSV2Instrumentor(&cfg.APIOptions)
  21. // Using the Config value, create the DynamoDB client
  22. svc := dynamodb.NewFromConfig(cfg)
  23. // Build the request with its input parameters
  24. _, err = svc.ListTables(ctx, &dynamodb.ListTablesInput{
  25. Limit: aws.Int32(5),
  26. })
  27. if err != nil {
  28. log.Fatalf("failed to list tables, %v", err)
  29. }
  30. }

Segment creation is not necessary in an AWS Lambda function, where the segment is created automatically

S3

aws-xray-sdk-go does not currently support *Request.Presign() operations and will panic if one is encountered. This results in an error similar to:

panic: failed to begin subsegment named 's3': segment cannot be found.

If you encounter this, you can set AWS_XRAY_CONTEXT_MISSING environment variable to LOG_ERROR. This will instruct the SDK to log the error and continue processing your requests.

  1. os.Setenv("AWS_XRAY_CONTEXT_MISSING", "LOG_ERROR")

SQL

Any database/sql calls can be traced with X-Ray by replacing the sql.Open call with xray.SQLContext. It is recommended to use URLs instead of configuration strings if possible.

  1. func main() {
  2. db, err := xray.SQLContext("postgres", "postgres://user:password@host:port/db")
  3. row, err := db.QueryRowContext(ctx, "SELECT 1") // Use as normal
  4. }

Lambda

  1. For Lambda support use version v1.0.0-rc.1 and higher

If you are using the AWS X-Ray Go SDK inside a Lambda function, there will be a FacadeSegment inside the Lambda context. This allows you to instrument your Lambda function using Configure, Capture, HTTP Client, AWS, SQL and Custom Subsegments usage. Segment operations are not supported.

  1. func HandleRequest(ctx context.Context, name string) (string, error) {
  2. sess := session.Must(session.NewSession())
  3. dynamo := dynamodb.New(sess)
  4. xray.AWS(dynamo.Client)
  5. input := &dynamodb.PutItemInput{
  6. Item: map[string]*dynamodb.AttributeValue{
  7. "12": {
  8. S: aws.String("example"),
  9. },
  10. },
  11. TableName: aws.String("xray"),
  12. }
  13. _, err := dynamo.PutItemWithContext(ctx, input)
  14. if err != nil {
  15. return name, err
  16. }
  17. _, err = ctxhttp.Get(ctx, xray.Client(nil), "https://www.twitch.tv/")
  18. if err != nil {
  19. return name, err
  20. }
  21. _, subseg := xray.BeginSubsegment(ctx, "subsegment-name")
  22. subseg.Close(nil)
  23. db := xray.SQLContext("postgres", "postgres://user:password@host:port/db")
  24. row, _ := db.QueryRow(ctx, "SELECT 1")
  25. return fmt.Sprintf("Hello %s!", name), nil
  26. }

gRPC

Note: aws-xray-sdk-go doesn’t currently support streaming gRPC call.

Apply xray gRPC interceptors (xray.UnaryServerInterceptor or xray.UnaryClientInterceptor) to instrument gRPC unary requests/responses, and the handling code.

gRPC Client

  1. conn, err := grpc.Dial(
  2. serverAddr,
  3. // use grpc.WithChainUnaryInterceptor instead to apply multiple interceptors
  4. grpc.WithUnaryInterceptor(
  5. xray.UnaryClientInterceptor(),
  6. // or xray.UnaryClientInterceptor(xray.WithSegmentNamer(xray.NewFixedSegmentNamer("myApp"))) to use a custom segment namer
  7. ),
  8. )

gRPC Server

  1. grpcServer := grpc.NewServer(
  2. // use grpc.ChainUnaryInterceptor instead to apply multiple interceptors
  3. grpc.UnaryInterceptor(
  4. xray.UnaryServerInterceptor(),
  5. // or xray.UnaryServerInterceptor(xray.WithSegmentNamer(xray.NewFixedSegmentNamer("myApp"))) to use a custom segment namer
  6. ),
  7. )

fasthttp instrumentation

Support for incoming requests with valyala/fasthttp:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "github.com/aws/aws-xray-sdk-go/v2/xray"
  7. "github.com/aws/aws-xray-sdk-go/v2/xraylog"
  8. "github.com/fasthttp/router"
  9. "github.com/valyala/fasthttp"
  10. )
  11. func index(ctx *fasthttp.RequestCtx) {
  12. ctx.WriteString("Welcome!")
  13. }
  14. func hello(ctx *fasthttp.RequestCtx) {
  15. fmt.Fprintf(ctx, "Hello, %s!\n", ctx.UserValue("name"))
  16. }
  17. func middleware(name string, h fasthttp.RequestHandler, fh xray.FastHTTPHandler) fasthttp.RequestHandler {
  18. f := func(ctx *fasthttp.RequestCtx) {
  19. h(ctx)
  20. }
  21. return fh.Handler(xray.NewFixedSegmentNamer(name), f)
  22. }
  23. func init() {
  24. if err := xray.Configure(xray.Config{
  25. DaemonAddr: "xray:2000",
  26. ServiceVersion: "0.1",
  27. }); err != nil {
  28. panic(err)
  29. }
  30. xray.SetLogger(xraylog.NewDefaultLogger(os.Stdout, xraylog.LogLevelDebug))
  31. }
  32. func main() {
  33. fh := xray.NewFastHTTPInstrumentor(nil)
  34. r := router.New()
  35. r.GET("/", middleware("index", index, fh))
  36. r.GET("/hello/{name}", middleware("hello", hello, fh))
  37. log.Fatal(fasthttp.ListenAndServe(":8080", r.Handler))
  38. }

Oversampling Mitigation

Oversampling mitigation allows you to ignore a parent segment/subsegment’s sampled flag and instead sets the subsegment’s sampled flag to false.
This ensures that downstream calls are not sampled and this subsegment is not emitted.

  1. import (
  2. "context"
  3. "fmt"
  4. "github.com/aws/aws-lambda-go/events"
  5. "github.com/aws/aws-lambda-go/lambda"
  6. "github.com/aws/aws-sdk-go/aws/session"
  7. "github.com/aws/aws-sdk-go/service/sqs"
  8. "github.com/aws/aws-xray-sdk-go/v2/xray"
  9. )
  10. func HandleRequest(ctx context.Context, event events.SQSEvent) (string, error) {
  11. _, subseg := xray.BeginSubsegmentWithoutSampling(ctx, "Processing Event")
  12. sess := session.Must(session.NewSessionWithOptions(session.Options{
  13. SharedConfigState: session.SharedConfigEnable,
  14. }))
  15. svc := sqs.New(sess)
  16. result, _ := svc.ListQueues(nil)
  17. for _, url := range result.QueueUrls {
  18. fmt.Printf("%s\n", *url)
  19. }
  20. subseg.Close(nil)
  21. return "Success", nil
  22. }
  23. func main() {
  24. lambda.Start(HandleRequest)
  25. }

The code below demonstrates overriding the sampled flag based on the SQS messages sent to Lambda.

  1. import (
  2. "context"
  3. "fmt"
  4. "strconv"
  5. "github.com/aws/aws-lambda-go/events"
  6. "github.com/aws/aws-lambda-go/lambda"
  7. xrayLambda "github.com/aws/aws-xray-sdk-go/v2/lambda"
  8. "github.com/aws/aws-xray-sdk-go/v2/xray"
  9. )
  10. func HandleRequest(ctx context.Context, event events.SQSEvent) (string, error) {
  11. var i = 1
  12. for _, message := range event.Records {
  13. var subseg *xray.Segment
  14. if xrayLambda.IsSampled(message) {
  15. _, subseg = xray.BeginSubsegment(ctx, "Processing Message - " + strconv.Itoa(i))
  16. } else {
  17. _, subseg = xray.BeginSubsegmentWithoutSampling(ctx, "Processing Message - " + strconv.Itoa(i))
  18. }
  19. i++;
  20. // Do your procesing work here
  21. fmt.Println("Doing processing work")
  22. // End your subsegment
  23. subseg.Close(nil)
  24. }
  25. return "Success", nil
  26. }
  27. func main() {
  28. lambda.Start(HandleRequest)
  29. }

License

The AWS X-Ray SDK for Go is licensed under the Apache 2.0 License. See LICENSE and NOTICE.txt for more information.