{"id":13526877,"url":"https://github.com/aws/aws-xray-sdk-go","last_synced_at":"2025-05-14T21:05:52.860Z","repository":{"id":24557013,"uuid":"97753296","full_name":"aws/aws-xray-sdk-go","owner":"aws","description":"AWS X-Ray SDK for the Go programming language.","archived":false,"fork":false,"pushed_at":"2025-05-02T23:55:09.000Z","size":952,"stargazers_count":281,"open_issues_count":53,"forks_count":116,"subscribers_count":18,"default_branch":"master","last_synced_at":"2025-05-08T00:08:00.951Z","etag":null,"topics":["aws","aws-xray","go"],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/aws.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2017-07-19T19:24:10.000Z","updated_at":"2025-05-06T14:56:38.000Z","dependencies_parsed_at":"2023-12-26T22:20:34.669Z","dependency_job_id":"25fd0657-9817-4df0-a3dd-6c440216aed1","html_url":"https://github.com/aws/aws-xray-sdk-go","commit_stats":{"total_commits":350,"total_committers":67,"mean_commits":5.223880597014926,"dds":0.7885714285714286,"last_synced_commit":"7ae28931182316fd0fa6960008a8c5edd1d82e71"},"previous_names":[],"tags_count":38,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aws%2Faws-xray-sdk-go","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aws%2Faws-xray-sdk-go/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aws%2Faws-xray-sdk-go/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aws%2Faws-xray-sdk-go/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/aws","download_url":"https://codeload.github.com/aws/aws-xray-sdk-go/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254227611,"owners_count":22035669,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws","aws-xray","go"],"created_at":"2024-08-01T06:01:36.586Z","updated_at":"2025-05-14T21:05:52.826Z","avatar_url":"https://github.com/aws.png","language":"Go","funding_links":[],"categories":["Go","Repositories"],"sub_categories":[],"readme":"![Test](https://github.com/aws/aws-xray-sdk-go/workflows/Test/badge.svg)\n[![Go Report Card](https://goreportcard.com/badge/github.com/aws/aws-xray-sdk-go)](https://goreportcard.com/report/github.com/aws/aws-xray-sdk-go)\n\n### :mega: OpenTelemetry Go with AWS X-Ray\n\nAWS 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](https://docs.aws.amazon.com/xray/latest/devguide/xray-instrumenting-your-app.html#xray-instrumenting-choosing) for more help with choosing between the two.\n\nIf you want additional features when tracing your Go applications, please [open an issue on the OpenTelemetry Go Instrumentation repository](https://github.com/open-telemetry/opentelemetry-go-contrib/issues/new?title=X-Ray%20Compatible%20Feature%20Request).\n\n# AWS X-Ray SDK for Go\n\n![Screenshot of the AWS X-Ray console](/images/example.png?raw=true)\n\n## Installing into GOPATH\n\nThe AWS X-Ray SDK for Go is compatible with Go 1.23 and above.\n\nInstall the SDK using the following command (The SDK's non-testing dependencies will be installed):\nUse `go get` to retrieve the SDK to add it to your `GOPATH` workspace:\n\n```\ngo get github.com/aws/aws-xray-sdk-go/v2\n```\n\nTo update the SDK, use `go get -u` to retrieve the latest version of the SDK.\n\n```\ngo get -u github.com/aws/aws-xray-sdk-go/v2\n```\n\nIf you also want to install SDK's testing dependencies. They can be installed using:\n\n```\ngo get -u -t github.com/aws/aws-xray-sdk-go/v2/...\n```\n\n## Installing using Go Modules\n\nThe latest version of the SDK is the recommended version.\n\nIf you are using Go 1.11 and above, you can install the SDK using Go Modules (in project's go.mod), like so: \n\n```\ngo get github.com/aws/aws-xray-sdk-go/v2\n```\n\nTo get a different specific release version of the SDK use `@\u003ctag\u003e` in your `go get` command. Also, to get the rc version use this command with the specific version.\n\n```\ngo get github.com/aws/aws-xray-sdk-go@v1.0.0\n```\n\n## Getting Help\n\nPlease use these community resources for getting help. We use the GitHub issues for tracking bugs and feature requests.\n\n* Ask a question in the [AWS X-Ray Forum](https://forums.aws.amazon.com/forum.jspa?forumID=241\u0026start=0).\n* Open a support ticket with [AWS Support](http://docs.aws.amazon.com/awssupport/latest/user/getting-started.html).\n* If you think you may have found a bug, please open an [issue](https://github.com/aws/aws-xray-sdk-go/issues/new).\n\n## Opening Issues\n\nIf you encounter a bug with the AWS X-Ray SDK for Go we would like to hear about it. Search the [existing issues](https://github.com/aws/aws-xray-sdk-go/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.\n\nThe 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](https://github.com/aws/aws-xray-sdk-go#getting-help) section. Keeping the list of open issues lean will help us respond in a timely manner.\n\n## Documentation\n\nThe [developer guide](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-go.html) provides in-depth guidance on using the AWS X-Ray service and the AWS X-Ray SDK for Go.\n\nSee [aws-xray-sdk-go-sample](https://github.com/aws-samples/aws-xray-sdk-go-sample) for a sample application that provides example of tracing SQL queries, incoming and outgoing request. Follow [README instructions](https://github.com/aws-samples/aws-xray-sdk-go-sample/blob/master/README.md) in that repository to get started with sample application.\n\n## Quick Start\n\n**Configuration**\n\n```go\nimport \"github.com/aws/aws-xray-sdk-go/v2/xray\"\n\nfunc init() {\n  xray.Configure(xray.Config{\n    DaemonAddr:       \"127.0.0.1:2000\", // default\n    ServiceVersion:   \"1.2.3\",\n  })\n}\n```\n***Logger***\n\nxray uses an interface for its logger:\n\n```go\ntype Logger interface {\n  Log(level LogLevel, msg fmt.Stringer)\n}\n\nconst (\n  LogLevelDebug LogLevel = iota + 1\n  LogLevelInfo\n  LogLevelWarn\n  LogLevelError\n)\n```\n\nThe default logger logs to [stdout](https://golang.org/pkg/syscall/#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:\n\n```go\nxray.SetLogger(xraylog.NewDefaultLogger(os.Stderr, xraylog.LogLevelError))\n```\n\nNote that the `xray.Config{}` fields `LogLevel` and `LogFormat` are deprecated starting from version `1.0.0-rc.10` and no longer have any effect.\n\n***Plugins***\n\nPlugins 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:\n\n```go\nimport (\n  \"os\"\n\n  \"github.com/aws/aws-xray-sdk-go/v2/awsplugins/ec2\"\n  \"github.com/aws/aws-xray-sdk-go/v2/xray\"\n)\n\nfunc init() {\n  // conditionally load plugin\n  if os.Getenv(\"ENVIRONMENT\") == \"production\" {\n    ec2.Init()\n  }\n\n  xray.Configure(xray.Config{\n    ServiceVersion:   \"1.2.3\",\n  })\n}\n```\n\n**Start a custom segment/subsegment**\nNote that customers using xray.BeginSegment API directly will only be able to evaluate sampling rules based on service name.\n\n```go\n  // Start a segment\n  ctx, seg := xray.BeginSegment(context.Background(), \"service-name\")\n  // Start a subsegment\n  subCtx, subSeg := xray.BeginSubsegment(ctx, \"subsegment-name\")\n  // ...\n  // Add metadata or annotation here if necessary\n  // ...\n  subSeg.Close(nil)\n  // Close the segment\n  seg.Close(nil)\n```\n\n**Generate no-op trace and segment id**\n\nX-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.\n\n**Disabling XRay Tracing**\n\nXRay 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.\n\n\n\n```go\n  // Set environment variable TRUE to disable XRay\n  os.Setenv(\"AWS_XRAY_SDK_DISABLED\", \"TRUE\")\n```\n\n**Capture**\n\n```go\nfunc criticalSection(ctx context.Context) {\n  // This example traces a critical code path using a custom subsegment\n  xray.Capture(ctx, \"MyService.criticalSection\", func(ctx1 context.Context) error {\n    var err error\n\n    section.Lock()\n    result := someLockedResource.Go()\n    section.Unlock()\n\n    xray.AddMetadata(ctx1, \"ResourceResult\", result)\n  })\n}\n```\n\n**HTTP Handler**\n\n```go\nfunc main() {\n  http.Handle(\"/\", xray.Handler(xray.NewFixedSegmentNamer(\"myApp\"), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n    w.Write([]byte(\"Hello!\"))\n  })))\n  http.ListenAndServe(\":8000\", nil)\n}\n```\n\n**HTTP Client**\n\n```go\nfunc getExample(ctx context.Context) ([]byte, error) {\n  resp, err := ctxhttp.Get(ctx, xray.Client(nil), \"https://aws.amazon.com/\")\n  if err != nil {\n    return nil, err\n  }\n  return ioutil.ReadAll(resp.Body)\n}\n```\n\n**AWS SDK Instrumentation**\n\n\u003e [!WARNING]\n\u003e Support for AWS SDK V1 Instrumentation has been removed in v2.0.0 of the AWS X-Ray SDK for Go\n\n```go\nfunc main() {\n  // Create a segment\n  ctx, root := xray.BeginSegment(context.TODO(), \"AWSSDKV1_Dynamodb\")\n  defer root.Close(nil)\n\n  sess := session.Must(session.NewSession())\n  dynamo := dynamodb.New(sess)\n  // Instrumenting with AWS SDK v1:\n  // Wrap the client object with `xray.AWS()`\n  xray.AWS(dynamo.Client)\n  // Use the `-WithContext` version of the `ListTables` method\n  output := dynamo.ListTablesWithContext(ctx, \u0026dynamodb.ListTablesInput{})\n  doSomething(output)\n}\n```\n*Segment creation is not necessary in an AWS Lambda function, where the segment is created automatically*\n\n**AWS SDK V2 Instrumentation**\n\n```go\npackage main\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"github.com/aws/aws-sdk-go-v2/aws\"\n\t\"github.com/aws/aws-sdk-go-v2/config\"\n\t\"github.com/aws/aws-sdk-go-v2/service/dynamodb\"\n\t\"github.com/aws/aws-xray-sdk-go/v2/instrumentation/awsv2\"\n\t\"github.com/aws/aws-xray-sdk-go/v2/xray\"\n)\n\nfunc main() {\n\t// Create a segment\n\tctx, root := xray.BeginSegment(context.TODO(), \"AWSSDKV2_Dynamodb\")\n\tdefer root.Close(nil)\n  \n\tcfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(\"us-west-2\"))\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to load SDK config, %v\", err)\n\t}\n\t// Instrumenting AWS SDK v2\n\tawsv2.AWSV2Instrumentor(\u0026cfg.APIOptions)\n\t// Using the Config value, create the DynamoDB client\n\tsvc := dynamodb.NewFromConfig(cfg)\n\t// Build the request with its input parameters\n\t_, err = svc.ListTables(ctx, \u0026dynamodb.ListTablesInput{\n\t\tLimit: aws.Int32(5),\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to list tables, %v\", err)\n\t}\n}\n```\n*Segment creation is not necessary in an AWS Lambda function, where the segment is created automatically*\n\n**S3**\n\n`aws-xray-sdk-go` does not currently support [`*Request.Presign()`](https://docs.aws.amazon.com/sdk-for-go/api/aws/request/#Request.Presign) operations and will panic if one is encountered.  This results in an error similar to: \n\n`panic: failed to begin subsegment named 's3': segment cannot be found.`\n\nIf 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.\n\n```go\nos.Setenv(\"AWS_XRAY_CONTEXT_MISSING\", \"LOG_ERROR\")\n```\n\n**SQL**\n\nAny `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.\n\n```go\nfunc main() {\n  db, err := xray.SQLContext(\"postgres\", \"postgres://user:password@host:port/db\")\n  row, err := db.QueryRowContext(ctx, \"SELECT 1\") // Use as normal\n}\n```\n\n**Lambda**\n\n```\nFor Lambda support use version v1.0.0-rc.1 and higher\n```\n\nIf 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.\n\n```go\nfunc HandleRequest(ctx context.Context, name string) (string, error) {\n    sess := session.Must(session.NewSession())\n    dynamo := dynamodb.New(sess)\n    xray.AWS(dynamo.Client)\n    input := \u0026dynamodb.PutItemInput{\n        Item: map[string]*dynamodb.AttributeValue{\n            \"12\": {\n                S: aws.String(\"example\"),\n            },\n        },\n        TableName: aws.String(\"xray\"),\n    }\n    _, err := dynamo.PutItemWithContext(ctx, input)\n    if err != nil {\n        return name, err\n    }\n    \n    _, err = ctxhttp.Get(ctx, xray.Client(nil), \"https://www.twitch.tv/\")\n    if err != nil {\n        return name, err\n    }\n    \n    _, subseg := xray.BeginSubsegment(ctx, \"subsegment-name\")\n    subseg.Close(nil)\n    \n    db := xray.SQLContext(\"postgres\", \"postgres://user:password@host:port/db\")\n    row, _ := db.QueryRow(ctx, \"SELECT 1\")\n    \n    return fmt.Sprintf(\"Hello %s!\", name), nil\n}\n```\n\n**gRPC**\n\nNote: `aws-xray-sdk-go` doesn't currently support streaming gRPC call.\n\nApply xray gRPC interceptors (`xray.UnaryServerInterceptor` or `xray.UnaryClientInterceptor`) to instrument gRPC unary requests/responses, and the handling code.\n\n**gRPC Client**\n\n```go\nconn, err := grpc.Dial(\n    serverAddr,\n    // use grpc.WithChainUnaryInterceptor instead to apply multiple interceptors\n    grpc.WithUnaryInterceptor(\n        xray.UnaryClientInterceptor(),\n        // or xray.UnaryClientInterceptor(xray.WithSegmentNamer(xray.NewFixedSegmentNamer(\"myApp\"))) to use a custom segment namer\n    ),\n)\n```\n\n**gRPC Server**\n\n```go\ngrpcServer := grpc.NewServer(\n    // use grpc.ChainUnaryInterceptor instead to apply multiple interceptors\n    grpc.UnaryInterceptor(\n        xray.UnaryServerInterceptor(),\n        // or xray.UnaryServerInterceptor(xray.WithSegmentNamer(xray.NewFixedSegmentNamer(\"myApp\"))) to use a custom segment namer\n    ),\n)\n```\n\n## fasthttp instrumentation \n\nSupport for incoming requests with [valyala/fasthttp](https://github.com/valyala/fasthttp):\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/aws/aws-xray-sdk-go/v2/xray\"\n\t\"github.com/aws/aws-xray-sdk-go/v2/xraylog\"\n\t\"github.com/fasthttp/router\"\n\t\"github.com/valyala/fasthttp\"\n)\n\nfunc index(ctx *fasthttp.RequestCtx) {\n\tctx.WriteString(\"Welcome!\")\n}\n\nfunc hello(ctx *fasthttp.RequestCtx) {\n\tfmt.Fprintf(ctx, \"Hello, %s!\\n\", ctx.UserValue(\"name\"))\n}\n\nfunc middleware(name string, h fasthttp.RequestHandler, fh xray.FastHTTPHandler) fasthttp.RequestHandler {\n\tf := func(ctx *fasthttp.RequestCtx) {\n\t\th(ctx)\n\t}\n\n\treturn fh.Handler(xray.NewFixedSegmentNamer(name), f)\n}\n\nfunc init() {\n\tif err := xray.Configure(xray.Config{\n\t\tDaemonAddr:     \"xray:2000\",\n\t\tServiceVersion: \"0.1\",\n\t}); err != nil {\n\t\tpanic(err)\n\t}\n\n\txray.SetLogger(xraylog.NewDefaultLogger(os.Stdout, xraylog.LogLevelDebug))\n}\n\nfunc main() {\n\tfh := xray.NewFastHTTPInstrumentor(nil)\n\tr := router.New()\n\tr.GET(\"/\", middleware(\"index\", index, fh))\n\tr.GET(\"/hello/{name}\", middleware(\"hello\", hello, fh))\n\n\tlog.Fatal(fasthttp.ListenAndServe(\":8080\", r.Handler))\n}\n```\n\n## Oversampling Mitigation\nOversampling mitigation allows you to ignore a parent segment/subsegment's sampled flag and instead sets the subsegment's sampled flag to false.\nThis ensures that downstream calls are not sampled and this subsegment is not emitted.\n\n```go\nimport (\n    \"context\"\n    \"fmt\"\n    \"github.com/aws/aws-lambda-go/events\"\n    \"github.com/aws/aws-lambda-go/lambda\"\n    \"github.com/aws/aws-sdk-go/aws/session\"\n    \"github.com/aws/aws-sdk-go/service/sqs\"\n    \"github.com/aws/aws-xray-sdk-go/v2/xray\"\n)\n\nfunc HandleRequest(ctx context.Context, event events.SQSEvent) (string, error) {\n    _, subseg := xray.BeginSubsegmentWithoutSampling(ctx, \"Processing Event\")\n\n    sess := session.Must(session.NewSessionWithOptions(session.Options{\n        SharedConfigState: session.SharedConfigEnable,\n    }))\n\n    svc := sqs.New(sess)\n\n    result, _ := svc.ListQueues(nil)\n\n    for _, url := range result.QueueUrls {\n        fmt.Printf(\"%s\\n\", *url)\n    }\n\n    subseg.Close(nil)\n\n    return \"Success\", nil\n}\n\nfunc main() {\n    lambda.Start(HandleRequest)\n}\n```\n\nThe code below demonstrates overriding the sampled flag based on the SQS messages sent to Lambda.\n\n```go\nimport (\n    \"context\"\n    \"fmt\"\n    \"strconv\"\n    \"github.com/aws/aws-lambda-go/events\"\n    \"github.com/aws/aws-lambda-go/lambda\"\n    xrayLambda \"github.com/aws/aws-xray-sdk-go/v2/lambda\"\n    \"github.com/aws/aws-xray-sdk-go/v2/xray\"\n)\n\nfunc HandleRequest(ctx context.Context, event events.SQSEvent) (string, error) {\n\n    var i = 1\n\n    for _, message := range event.Records {\n        var subseg *xray.Segment\n\n        if xrayLambda.IsSampled(message) {\n            _, subseg = xray.BeginSubsegment(ctx, \"Processing Message - \" + strconv.Itoa(i))\n        } else {\n            _, subseg = xray.BeginSubsegmentWithoutSampling(ctx, \"Processing Message - \" + strconv.Itoa(i))\n        }\n\n        i++;\n\n        // Do your procesing work here\n        fmt.Println(\"Doing processing work\")\n\n        // End your subsegment\n        subseg.Close(nil)\n    }\n\n    return \"Success\", nil\n}\n\nfunc main() {\n    lambda.Start(HandleRequest)\n}\n```\n\n## License\n\nThe AWS X-Ray SDK for Go is licensed under the Apache 2.0 License. See LICENSE and NOTICE.txt for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faws%2Faws-xray-sdk-go","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faws%2Faws-xray-sdk-go","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faws%2Faws-xray-sdk-go/lists"}