X ray sdk

X ray sdk DEFAULT

AWS X-Ray SDK for Swift

pokryfka/aws-xray-sdk-swift

Unofficial AWS X-Ray SDK for Swift.

.package(url: "https://github.com/pokryfka/aws-xray-sdk-swift.git", from: "v0.7.1")

Buildcodecov

Unofficial AWS X-Ray SDK for Swift.

Project status

Functional beta.

At the moment the SDK does not support sampling rules, tracing can be either enabled or disabled (issue 57).

AWS X-Ray SDK for Swift follows SemVer. Until version 1.0.0 breaking changes may be introduced on minor version number changes.

Documentation

Getting started

Adding the dependency

Add the package dependency to your package Swift Package Manager manifest file :

and library to your target (here ):

Recording

Create an instance of and new context:

Begin and end (sub)segments explicitly:

use closures for convenience:

Errors and exceptions

You can record errors and exceptions:

Note that s thrown in the closures are recorded.

HTTP request data

You can record details about an HTTP request that your application served or made to a downstream HTTP API, see HTTP request data:

Annotations and Metadata

Segments and subsegments can include annotations:

and metadata:

Emitting

Events are emitted as soon as they end.

Subsegments have to be created before the parent segment ended.

Subsegments may end after their parent segment ended, in which case they will be presented as Pending until they end.

Make sure to shutdown the recorder before program exits:

You can flush it before :

or, if using SwiftNIO, on provided :

Result in AWS X-Ray console:

Screenshot of the AWS X-Ray console

See for a complete example.

Custom emitter

By default events are sent as UDP to AWS X-Ray daemon which buffers and relays them to AWS X-Ray API.

A custom emitter has to implement protocol:

it may also implement :

The emitter has to be provided when creating an instance of :

Context propagation

Unlike in other X-Ray SDKs, in AWS X-Ray SDK for Swift does not expose (thread local) current .

The context, in its broader meaning that is including but not limited to trace context, should be passed explicitly in :

You can create new X-Ray Context from tracing header:

or using provided (or generated) TraceID, parent segment and sampling decision:

You can update the X-Ray context in the baggage:

Note that the subject is currently under discussion by community:

XRayInstrument (WIP)

Integration with libraries in ecosystem is (will be) done using which implements defined in swift-tracing library.

As the API of is not stable, PoC implementation of is on branch.

Example:

Configuration

The libraries behavior can be configured using environment variables:

  • - set to disable tracing, enabled by default.
  • - the IP address and port of the X-Ray daemon listener, by default.
  • - configures how the SDK handles missing context:
    • - Indicate that a precondition was violated.
    • - Log an error and continue (default).
  • - recorder swift-log logging level, by default.
  • - emitter swift-log logging level, by default.

Alternatively can be configured using which will override environment variables:

Testing

You can run the AWS X-Ray daemon locally or in a Docker container, see Running the X-Ray daemon locally

You can use from to "emit" segments to the console:

Contributing

Code Formatting

Format code using swiftformat:

Consider creating Git pre-commit hook

Examples

AWS Lambda using Swift AWS Lambda Runtime

Enable tracing as described in Using AWS Lambda with AWS X-Ray.

Note that:

Lambda runs the daemon automatically any time a function is invoked for a sampled request.

Make sure to flush the recorder in each invocation:

See for a complete example.

Note that it will not be needed to create a recorder nor flush it when Swift AWS Lambda Runtime is instrumented, see PoC.

License

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

Sours: https://swiftpack.co/package/pokryfka/aws-xray-sdk-swift

npm

Requirements

  • AWS SDK v2.7.15 or greater (if using or )
  • Express 4.14.0 or greater (if using Express and the associated X-Ray middleware)
  • MySQL 2.12.0 or greater (if using )
  • Postgres 6.1.0 or greater (if using )

AWS X-Ray

The AWS X-Ray SDK automatically records information for incoming and outgoing requests and responses (via middleware), as well as local data such as function calls, time, variables (via metadata and annotations), even EC2 instance data (via plugins).

Although the AWS X-Ray SDK was originally intended to capture request/response data on a web app, the SDK provides functionality for use cases outside this as well. The SDK exposes the 'Segment' and 'Subsegment' objects to create your own capturing mechanisms, middleware, etc.

This package includes the following AWS X-Ray packages.

Setup

The core package contains the base SDK functionality. Please see the aws-xray-sdk-core README.md for more details.

Support for web frameworks

Sours: https://www.npmjs.com/package/aws-xray-sdk
  1. Mcpe external servers
  2. Police motto generator
  3. Binge audio
  4. Pressure washer mop
  • Constants
  • Variables
  • func AWS(c *client.Client)
  • func AWSSession(s *session.Session) *session.Session
  • func AWSSessionWithWhitelist(s *session.Session, filename string) *session.Session
  • func AWSWithWhitelist(c *client.Client, filename string)
  • func AddAnnotation(ctx context.Context, key string, value interface{}) error
  • func AddError(ctx context.Context, err error) error
  • func AddMetadata(ctx context.Context, key string, value interface{}) error
  • func AddMetadataToNamespace(ctx context.Context, namespace string, key string, value interface{}) error
  • func Capture(ctx context.Context, name string, fn func(context.Context) error) (err error)
  • func CaptureAsync(ctx context.Context, name string, fn func(context.Context) error)
  • func Client(c *http.Client) *http.Client
  • func Configure(c Config) error
  • func ContextWithConfig(ctx context.Context, c Config) (context.Context, error)
  • func DetachContext(ctx context.Context) context.Context
  • func Handler(sn SegmentNamer, h http.Handler) http.Handler
  • func HandlerWithContext(ctx context.Context, sn SegmentNamer, h http.Handler) http.Handler
  • func HttpCaptureResponse(seg *Segment, statusCode int)
  • func NewSegmentID() string
  • func NewTraceID() string
  • func RequestWasTraced(ctx context.Context) bool
  • func RoundTripper(rt http.RoundTripper) http.RoundTripper
  • func SQLConnector(dsn string, connector driver.Connector) driver.Connector
  • func SQLContext(driver, dsn string) (*sql.DB, error)
  • func SdkDisabled() bool
  • func SetLogger(l xraylog.Logger)
  • func TraceID(ctx context.Context) string
  • func UnaryClientInterceptor(clientInterceptorOptions ...GrpcOption) grpc.UnaryClientInterceptor
  • func UnaryServerInterceptor(serverInterceptorOptions ...GrpcOption) grpc.UnaryServerInterceptor
  • type CauseData
  • type ClientTrace
  • type Config
  • type ContextKeytype
  • type DefaultEmitter
  • type DefaultStreamingStrategy
  • type DynamicSegmentNamer
  • type Emitter
  • type FastHTTPHandler
  • type FixedSegmentNamer
  • type GrpcOption
  • type HTTPData
  • type HTTPSubsegments
  • type RecorderContextKey
  • type RequestData
  • type ResponseData
  • type SDK
  • type SQLData
  • type Segment
    • func BeginFacadeSegment(ctx context.Context, name string, h *header.Header) (context.Context, *Segment)
    • func BeginSegment(ctx context.Context, name string) (context.Context, *Segment)
    • func BeginSegmentWithSampling(ctx context.Context, name string, r *http.Request, traceHeader *header.Header) (context.Context, *Segment)
    • func BeginSubsegment(ctx context.Context, name string) (context.Context, *Segment)
    • func GetSegment(ctx context.Context) *Segment
    • func NewSegmentFromHeader(ctx context.Context, name string, r *http.Request, h *header.Header) (context.Context, *Segment)
  • type SegmentNamer
  • type ServiceData
  • type StreamingStrategy

ExtendedRequestIDKey is the key name of the extend request id.

Header is added before sending segments to daemon.

LambdaTaskRootKey is the key to get Lambda Task Root from environment variable.

LambdaTraceHeaderKey is key to get trace header from context.

RequestIDKey is the key name of the request id.

S3ExtendedRequestIDHeaderKey is the key name of the s3 extend request id.

SDKInitializedFileFolder records the location of SDK initialized file.

SDKInitializedFileName records the SDK initialized file name.

SDKType records which X-Ray SDK customer uses.

SDKVersion records the current X-Ray Go SDK version.

TraceIDHeaderKey is the HTTP header name used for tracing.

ContextKey returns a pointer to a newly allocated zero value of ContextKeytype.

ErrRetrieveSegment happens when a segment cannot be retrieved

AWS adds X-Ray tracing to an AWS client.

AWSSession adds X-Ray tracing to an AWS session. Clients created under this session will inherit X-Ray tracing.

AWSWithWhitelist allows a custom parameter whitelist JSON file to be defined.

AddAnnotation adds an annotation to the provided segment or subsegment in ctx.

AddError adds an error to the provided segment or subsegment in ctx.

AddMetadata adds a metadata to the provided segment or subsegment in ctx.

AddMetadataToNamespace adds a namespace to the provided segment's or subsegment's metadata in ctx.

CaptureAsync traces an arbitrary code segment within a goroutine. Use CaptureAsync instead of manually calling Capture within a goroutine to ensure the segment is flushed properly.

Client creates a shallow copy of the provided http client, defaulting to http.DefaultClient, with roundtripper wrapped with xray.RoundTripper.

Configure overrides default configuration options with customer-defined values.

DetachContext returns a new context with the existing segment. This is useful for creating background tasks which won't be cancelled when a request completes.

func Handler¶

Handler wraps the provided http handler with xray.Capture using the request's context, parsing the incoming headers, adding response headers if needed, and sets HTTP specific trace fields. Handler names the generated segments using the provided SegmentNamer.

func HandlerWithContext¶added inv1.0.0

HandlerWithContext wraps the provided http handler and context to parse the incoming headers, add response headers if needed, and sets HTTP specific trace fields. HandlerWithContext names the generated segments using the provided SegmentNamer.

func HttpCaptureResponse(seg *Segment, statusCode int)

HttpCaptureResponse fill response by http status code

NewSegmentID generates a string format of segment ID.

NewTraceID generates a string format of random trace ID.

RequestWasTraced returns true if the context contains an X-Ray segment that was created from an HTTP request that contained a trace header. This is useful to ensure that a service is only called from X-Ray traced services.

RoundTripper wraps the provided http roundtripper with xray.Capture, sets HTTP-specific xray fields, and adds the trace header to the outbound request.

SQLConnector wraps the connector, and traces SQL executions. Unlike SQLContext, SQLConnector doesn't filter the password of the dsn. So, you have to filter the password before passing the dsn to SQLConnector.

SQLContext opens a normalized and traced wrapper around an *sql.DB connection. It uses `sql.Open` internally and shares the same function signature. To ensure passwords are filtered, it is HIGHLY RECOMMENDED that your DSN follows the format: `<schema>://<user>:<password>@<host>:<port>/<database>`

Check if SDK is disabled

SetLogger sets the logger instance used by xray. Only set from init() functions as SetLogger is not goroutine safe.

TraceID returns the canonical ID of the cross-service trace from the given segment in ctx. The value can be used in X-Ray's UI to uniquely identify the code paths executed. If no segment is provided in ctx, an empty string is returned.

type CauseData struct { WorkingDirectory string `json:"working_directory,omitempty"` Paths []string `json:"paths,omitempty"` Exceptions []exception.Exception `json:"exceptions,omitempty"` }

CauseData provides the shape for unmarshalling data that records exception.

type ClientTrace struct { }

ClientTrace is a set of pointers of HTTPSubsegments and ClientTrace.

NewClientTrace returns an instance of xray.ClientTrace, a wrapper around httptrace.ClientTrace. The ClientTrace implementation will generate subsegments for connection time, DNS lookup time, TLS handshake time, and provides additional information about the HTTP round trip

ContextKeytype defines integer to be type of ContextKey.

DefaultEmitter provides the naive implementation of emitting trace entities.

NewDefaultEmitter initializes and returns a pointer to an instance of DefaultEmitter.

Emit segment or subsegment if root segment is sampled. seg has a write lock acquired by the caller.

RefreshEmitterWithAddress dials UDP based on the input UDP address.

type DefaultStreamingStrategy struct { MaxSubsegmentCount uint32}

DefaultStreamingStrategy provides a default value of 20 for the maximum number of subsegments that can be emitted in a single UDP packet.

NewDefaultStreamingStrategy initializes and returns a pointer to an instance of DefaultStreamingStrategy.

NewDefaultStreamingStrategyWithMaxSubsegmentCount initializes and returns a pointer to an instance of DefaultStreamingStrategy with a custom maximum number of subsegments per UDP packet.

RequiresStreaming returns true when the number of subsegment children for a given segment is larger than MaxSubsegmentCount.

StreamCompletedSubsegments separates subsegments from the provided segment tree and sends them to daemon as streamed subsegment UDP packets.

type DynamicSegmentNamer struct { FallbackName string RecognizedHosts string}

DynamicSegmentNamer chooses names for segments generated for incoming requests by parsing the HOST header of the incoming request. If the host header matches a given recognized pattern (using the included pattern package), it is used as the segment name. Otherwise, the fallback name is used.

type Emitter interface { Emit(seg *Segment) RefreshEmitterWithAddress(raddr *net.UDPAddr) }

Emitter provides an interface for implementing emitting trace entities.

type FixedSegmentNamer struct { FixedName string}

FixedSegmentNamer records the fixed name of service node.

NewFixedSegmentNamer initializes a FixedSegmentNamer which will provide a fixed segment name for every generated segment. If the AWS_XRAY_TRACING_NAME environment variable is set, its value will override the provided name argument.

Name returns the segment name for the given host header value. In this case, FixedName is always returned.

type GrpcOption interface { }

WithRecorder configures the instrumentation by given xray.Config.

WithSegmentNamer makes the interceptor use the segment namer to name the segment.

type HTTPData struct { Request *RequestData `json:"request,omitempty"` Response *ResponseData `json:"response,omitempty"` }

HTTPData provides the shape for unmarshalling request and response data.

type HTTPSubsegments struct { }

HTTPSubsegments is a set of context in different HTTP operation. Note: from ClientTrace godoc

Functions may be called concurrently from different goroutines

HTTPSubsegments must operate as though all functions on it can be called in different goroutines and must protect against races

NewHTTPSubsegments creates a new HTTPSubsegments to use in httptrace.ClientTrace functions

ConnectDone closes the dial subsegment if the HTTP operation subsegment is still in progress, passing the error value (if any). Information about the network over which the dial was made is added as metadata to the subsegment.

ConnectStart begins a dial subsegment if the HTTP operation subsegment is still in progress.

DNSDone closes the dns subsegment if the HTTP operation subsegment is still in progress, passing the error value (if any). Information about the address values looked up, and whether or not the call was coalesced is added as metadata to the dns subsegment.

GetConn begins a connect subsegment if the HTTP operation subsegment is still in progress.

GotConn closes the connect subsegment if the HTTP operation subsegment is still in progress, passing the error value (if any). Information about the connection is added as metadata to the subsegment. If the connection is marked as reused, the connect subsegment is deleted.

GotFirstResponseByte closes the response subsegment if the HTTP operation subsegment is still in progress.

func (*HTTPSubsegments) TLSHandshakeDone¶added inv0.9.4

TLSHandshakeDone closes the tls subsegment if the HTTP operation subsegment is still in progress, passing the error value(if any). Information about the tls connection is added as metadata to the subsegment.

func (*HTTPSubsegments) TLSHandshakeStart¶added inv0.9.4

TLSHandshakeStart begins a tls subsegment if the HTTP operation subsegment is still in progress.

WroteRequest closes the request subsegment if the HTTP operation subsegment is still in progress, passing the error value (if any). The response subsegment is then begun.

type RecorderContextKey struct{}

RecorderContextKey records the key for Config value.

type RequestData struct { Method string `json:"method,omitempty"` URL string `json:"url,omitempty"` ClientIP string `json:"client_ip,omitempty"` UserAgent string `json:"user_agent,omitempty"` XForwardedFor bool `json:"x_forwarded_for,omitempty"` Traced bool `json:"traced,omitempty"` }

RequestData provides the shape for unmarshalling request data.

type ResponseData struct { Status int `json:"status,omitempty"` ContentLength int `json:"content_length,omitempty"` }

ResponseData provides the shape for unmarshalling response data.

type SDK struct { Version string `json:"sdk_version,omitempty"` Type string `json:"sdk,omitempty"` RuleName string `json:"sampling_rule_name,omitempty"` }

SDK provides the shape for unmarshalling an SDK struct.

type SQLData struct { ConnectionString string `json:"connection_string,omitempty"` URL string `json:"url,omitempty"` DatabaseType string `json:"database_type,omitempty"` DatabaseVersion string `json:"database_version,omitempty"` DriverVersion string `json:"driver_version,omitempty"` User string `json:"user,omitempty"` Preparation string `json:"preparation,omitempty"` SanitizedQuery string `json:"sanitized_query,omitempty"` }

SQLData provides the shape for unmarshalling sql data.

type Segment struct { sync.RWMutex Sampled bool `json:"-"` RequestWasTraced bool `json:"-"` ContextDone bool `json:"-"` Emitted bool `json:"-"` ParentSegment *Segment `json:"-"` TraceID string `json:"trace_id,omitempty"` ID string `json:"id"` Name string `json:"name"` StartTime float64 `json:"start_time"` EndTime float64 `json:"end_time,omitempty"` InProgress bool `json:"in_progress,omitempty"` ParentID string `json:"parent_id,omitempty"` Fault bool `json:"fault,omitempty"` Error bool `json:"error,omitempty"` Throttle bool `json:"throttle,omitempty"` Cause *CauseData `json:"cause,omitempty"` ResourceARN string `json:"resource_arn,omitempty"` Origin string `json:"origin,omitempty"` Type string `json:"type,omitempty"` Namespace string `json:"namespace,omitempty"` User string `json:"user,omitempty"` PrecursorIDs []string `json:"precursor_ids,omitempty"` HTTP *HTTPData `json:"http,omitempty"` AWS map[string]interface{} `json:"aws,omitempty"` Service *ServiceData `json:"service,omitempty"` SQL *SQLData `json:"sql,omitempty"` Annotations map[string]interface{} `json:"annotations,omitempty"` Metadata map[string]map[string]interface{} `json:"metadata,omitempty"` Subsegments []json.RawMessage `json:"subsegments,omitempty"` Configuration *Config `json:"-"` Facade bool `json:"-"` Dummy bool }

Segment provides the resource's name, details about the request, and details about the work done.

GetSegment returns a pointer to the segment or subsegment provided in ctx, or nil if no segment or subsegment is found.

AddAnnotation allows adding an annotation to the segment.

AddError allows adding an error to the segment.

AddMetadata allows adding metadata to the segment.

AddMetadataToNamespace allows adding a namespace into metadata for the segment.

AddRuleName adds rule name, if present from sampling decision to xray context.

func (*Segment) CloseAndStream¶added inv1.0.0

CloseAndStream closes a subsegment and sends it.

DownstreamHeader returns a header for passing to downstream calls.

GetAWS returns value of AWS.

GetConfiguration returns a value of Config.

RemoveSubsegment removes a subsegment child from a segment or subsegment.

SegmentNamer is the interface for naming service node.

type ServiceData struct { Version string `json:"version,omitempty"` RuntimeVersion string `json:"runtime_version,omitempty"` Runtime string `json:"runtime,omitempty"` }

ServiceData provides the shape for unmarshalling service version.

type StreamingStrategy interface { RequiresStreaming(seg *Segment) bool StreamCompletedSubsegments(seg *Segment) [][]byte}

StreamingStrategy provides an interface for implementing streaming strategies.

Sours: https://pkg.go.dev/github.com/aws/aws-xray-sdk-go/xray
Optimize Application Performance with AWS X-Ray

AWS X-Ray SDK for Python

Build Statuscodecov

Screenshot of the AWS X-Ray console

Installing

The AWS X-Ray SDK for Python is compatible with Python 2.7, 3.4, 3.5, 3.6, 3.7, 3.8, and 3.9.

Install the SDK using the following command (the SDK's non-testing dependencies will be installed).

To install the SDK's testing dependencies, use the following command.

Getting Help

Use the following community resources for getting help with the SDK. 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 Python, we want to hear about it. Before opening a new issue, search the existing issues to see if others are also experiencing the issue. Include the version of the AWS X-Ray SDK for Python, Python language, and botocore/boto3 if applicable. In addition, include the repro case when appropriate.

The GitHub issues are intended for bug reports and feature requests. For help and questions about using the AWS SDK for Python, use the resources listed in the Getting Help section. Keeping the list of open issues lean helps us respond in a timely manner.

Documentation

The developer guide provides in-depth guidance about using the AWS X-Ray service. The API Reference provides guidance for using the SDK and module-level documentation.

Quick Start

Configuration

fromaws_xray_sdk.coreimportxray_recorderxray_recorder.configure(sampling=False,context_missing='LOG_ERROR',plugins=('EC2Plugin','ECSPlugin','ElasticBeanstalkPlugin'),daemon_address='127.0.0.1:3000',dynamic_naming='*mysite.com*')

Start a custom segment/subsegment

Using context managers for implicit exceptions recording:

fromaws_xray_sdk.coreimportxray_recorderwithxray_recorder.in_segment('segment_name')assegment:# Add metadata or annotation here if necessarysegment.put_metadata('key',dict,'namespace')withxray_recorder.in_subsegment('subsegment_name')assubsegment:subsegment.put_annotation('key','value')# Do something herewithxray_recorder.in_subsegment('subsegment2')assubsegment:subsegment.put_annotation('key2','value2')# Do something else

async versions of context managers:

fromaws_xray_sdk.coreimportxray_recorderasyncwithxray_recorder.in_segment_async('segment_name')assegment:# Add metadata or annotation here if necessarysegment.put_metadata('key',dict,'namespace')asyncwithxray_recorder.in_subsegment_async('subsegment_name')assubsegment:subsegment.put_annotation('key','value')# Do something hereasyncwithxray_recorder.in_subsegment_async('subsegment2')assubsegment:subsegment.put_annotation('key2','value2')# Do something else

Default begin/end functions:

fromaws_xray_sdk.coreimportxray_recorder# Start a segmentsegment=xray_recorder.begin_segment('segment_name')# Start a subsegmentsubsegment=xray_recorder.begin_subsegment('subsegment_name')# Add metadata or annotation here if necessarysegment.put_metadata('key',dict,'namespace')subsegment.put_annotation('key','value')xray_recorder.end_subsegment()# Close the segmentxray_recorder.end_segment()

Capture

As a decorator:

[email protected]_recorder.capture('subsegment_name')defmyfunc():# Do something heremyfunc()

or as a context manager:

fromaws_xray_sdk.coreimportxray_recorderwithxray_recorder.capture('subsegment_name')assubsegment:# Do something heresubsegment.put_annotation('mykey',val)# Do something more

Async capture as decorator:

[email protected]_recorder.capture_async('subsegment_name')asyncdefmyfunc():# Do something hereasyncdefmain():awaitmyfunc()

or as context manager:

fromaws_xray_sdk.coreimportxray_recorderasyncwithxray_recorder.capture_async('subsegment_name')assubsegment:# Do something heresubsegment.put_annotation('mykey',val)# Do something more

Adding annotations/metadata using recorder

fromaws_xray_sdk.coreimportxray_recorder# Start a segment if no segment existsegment1=xray_recorder.begin_segment('segment_name')# This will add the key value pair to segment1 as it is activexray_recorder.put_annotation('key','value')# Start a subsegment so it becomes the active trace entitysubsegment1=xray_recorder.begin_subsegment('subsegment_name')# This will add the key value pair to subsegment1 as it is activexray_recorder.put_metadata('key','value')ifxray_recorder.is_sampled():# some expensitve annotations/metadata generation code hereval=compute_annotation_val()metadata=compute_metadata_body()xray_recorder.put_annotation('mykey',val)xray_recorder.put_metadata('mykey',metadata)

Generate NoOp Trace and Entity Id

X-Ray Python SDK will by default generate no-op trace and entity 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 should set the environment variable as False.

Disabling X-Ray

Often times, it may be useful to be able to disable X-Ray for specific use cases, whether to stop X-Ray from sending traces at any moment, or to test code functionality that originally depended on X-Ray instrumented packages to begin segments prior to the code call. For example, if your application relied on an XRayMiddleware to instrument incoming web requests, and you have a method which begins subsegments based on the segment generated by that middleware, it would be useful to be able to disable X-Ray for your unit tests so that exceptions are not thrown when you need to test your method.

There are two ways to disable X-Ray, one is through environment variables, and the other is through the SDKConfig module.

Disabling through the environment variable:

Prior to running your application, make sure to have the environment variable set to .

Disabling through the SDKConfig module:

Important Notes:

  • Environment Variables always take precedence over the SDKConfig module when disabling/enabling. If your environment variable is set to while your code calls , X-Ray will still be disabled.

  • If you need to re-enable X-Ray again during runtime and acknowledge disabling/enabling through the SDKConfig module, you may run the following in your application:

Trace AWS Lambda functions

fromaws_xray_sdk.coreimportxray_recorderdeflambda_handler(event,context):# ... some codesubsegment=xray_recorder.begin_subsegment('subsegment_name')# Code to record# Add metadata or annotation here, if necessarysubsegment.put_metadata('key',dict,'namespace')subsegment.put_annotation('key','value')xray_recorder.end_subsegment()# ... some other code

Trace ThreadPoolExecutor

importconcurrent.futuresimportrequestsfromaws_xray_sdk.coreimportxray_recorderfromaws_xray_sdk.coreimportpatchpatch(('requests',))URLS=['http://www.amazon.com/','http://aws.amazon.com/','http://example.com/','http://www.bilibili.com/','http://invalid-domain.com/']defload_url(url,trace_entity):# Set the parent X-Ray entity for the worker thread.xray_recorder.set_trace_entity(trace_entity)# Subsegment captured from the following HTTP GET will be# a child of parent entity passed from the main thread.resp=requests.get(url)# prevent thread pollutionxray_recorder.clear_trace_entities()returnresp# Get the current active segment or subsegment from the main thread.current_entity=xray_recorder.get_trace_entity()withconcurrent.futures.ThreadPoolExecutor(max_workers=5)asexecutor:# Pass the active entity from main thread to worker threads.future_to_url={executor.submit(load_url,url,current_entity):urlforurlinURLS}forfutureinconcurrent.futures.as_completed(future_to_url):url=future_to_url[future]try:data=future.result()exceptException:pass

Trace SQL queries

By default, if no other value is provided to , SQL trace streaming is enabled for all the supported DB engines. Those currently are:

  • Any engine attached to the Django ORM.
  • Any engine attached to SQLAlchemy.

The behaviour can be toggled by sending the appropriate value, for example:

fromaws_xray_sdk.coreimportxray_recorderxray_recorder.configure(service='fallback_name',stream_sql=True)

Patch third-party libraries

fromaws_xray_sdk.coreimportpatchlibs_to_patch=('boto3','mysql','requests')patch(libs_to_patch)

Automatic module patching

Full modules in the local codebase can be recursively patched by providing the module references to the patch function.

fromaws_xray_sdk.coreimportpatchlibs_to_patch=('boto3','requests','local.module.ref','other_module')patch(libs_to_patch)

An decorator will be applied to all functions and class methods in the given module and all the modules inside them recursively. Some files/modules can be excluded by providing to the function a regex that matches them.

fromaws_xray_sdk.coreimportpatchlibs_to_patch=('boto3','requests','local.module.ref','other_module')ignore=('local.module.ref.some_file','other_module.some_module\.*')patch(libs_to_patch,ignore_module_patterns=ignore)

Django

Add Django middleware

In django settings.py, use the following.

INSTALLED_APPS=[# ... other apps'aws_xray_sdk.ext.django',]MIDDLEWARE=['aws_xray_sdk.ext.django.middleware.XRayMiddleware',# ... other middlewares]

You can configure the X-Ray recorder in a Django app under the ‘XRAY_RECORDER’ namespace. For a minimal configuration, the 'AWS_XRAY_TRACING_NAME' is required unless it is specified in an environment variable.

For more information about configuring Django with X-Ray read more about it in the API reference

SQL tracing

If Django's ORM is patched - either using the in your settings file or explicitly calling - the SQL query trace streaming can then be enabled or disabled updating the variable in your settings file. It is enabled by default.

Automatic patching

The automatic module patching can also be configured through Django settings.

XRAY_RECORDER={'PATCH_MODULES':['boto3','requests','local.module.ref','other_module',],'IGNORE_MODULE_PATTERNS':['local.module.ref.some_file','other_module.some_module\.*',],...}

If is also specified, then a segment parent will be created with the supplied name, wrapping the automatic patching so that it captures any dangling subsegments created on the import patching.

Add Flask middleware

fromaws_xray_sdk.coreimportxray_recorderfromaws_xray_sdk.ext.flask.middlewareimportXRayMiddlewareapp=Flask(__name__)xray_recorder.configure(service='fallback_name',dynamic_naming='*mysite.com*')XRayMiddleware(app,xray_recorder)

Add Bottle middleware(plugin)

fromaws_xray_sdk.coreimportxray_recorderfromaws_xray_sdk.ext.bottle.middlewareimportXRayMiddlewareapp=Bottle()xray_recorder.configure(service='fallback_name',dynamic_naming='*mysite.com*')app.install(XRayMiddleware(xray_recorder))

Serverless Support for Flask & Django & Bottle Using X-Ray

Serverless is an application model that enables you to shift more of your operational responsibilities to AWS. As a result, you can focus only on your applications and services, instead of the infrastructure management tasks such as server provisioning, patching, operating system maintenance, and capacity provisioning. With serverless, you can deploy your web application to AWS Lambda and have customers interact with it through a Lambda-invoking endpoint, such as Amazon API Gateway.

X-Ray supports the Serverless model out of the box and requires no extra configuration. The middlewares in Lambda generate instead of when an endpoint is reached. This is because cannot be generated inside the Lambda function, but it is generated automatically by the Lambda container. Therefore, when using the middlewares with this model, it is important to make sure that your methods only generate .

The following guide shows an example of setting up a Serverless application that utilizes API Gateway and Lambda:

Instrumenting Web Frameworks in a Serverless Environment

Working with aiohttp

Adding aiohttp middleware. Support aiohttp >= 2.3.

fromaiohttpimportwebfromaws_xray_sdk.ext.aiohttp.middlewareimportmiddlewarefromaws_xray_sdk.coreimportxray_recorderfromaws_xray_sdk.core.async_contextimportAsyncContextxray_recorder.configure(service='fallback_name',context=AsyncContext())app=web.Application(middlewares=[middleware])app.router.add_get("/",handler)web.run_app(app)

Tracing aiohttp client. Support aiohttp >=3.

fromaws_xray_sdk.ext.aiohttp.clientimportaws_xray_trace_configasyncdeffoo():trace_config=aws_xray_trace_config()asyncwithClientSession(loop=loop,trace_configs=[trace_config])assession:asyncwithsession.get(url)asrespawaitresp.read()

Use SQLAlchemy ORM

The SQLAlchemy integration requires you to override the Session and Query Classes for SQL Alchemy

SQLAlchemy integration uses subsegments so you need to have a segment started before you make a query.

fromaws_xray_sdk.coreimportxray_recorderfromaws_xray_sdk.ext.sqlalchemy.queryimportXRaySessionMakerxray_recorder.begin_segment('SQLAlchemyTest')Session=XRaySessionMaker(bind=engine)session=Session()xray_recorder.end_segment()app=Flask(__name__)xray_recorder.configure(service='fallback_name',dynamic_naming='*mysite.com*')XRayMiddleware(app,xray_recorder)

Add Flask-SQLAlchemy

fromaws_xray_sdk.coreimportxray_recorderfromaws_xray_sdk.ext.flask.middlewareimportXRayMiddlewarefromaws_xray_sdk.ext.flask_sqlalchemy.queryimportXRayFlaskSqlAlchemyapp=Flask(__name__)app.config["SQLALCHEMY_DATABASE_URI"]="sqlite:///:memory:"XRayMiddleware(app,xray_recorder)db=XRayFlaskSqlAlchemy(app)

Ignoring httplib requests

If you want to ignore certain httplib requests you can do so based on the hostname or URL that is being requsted. The hostname is matched using the Python fnmatch library which does Unix glob style matching.

fromaws_xray_sdk.ext.httplibimportadd_ignoredasxray_add_ignored# ignore requests to test.myapp.comxray_add_ignored(hostname='test.myapp.com')# ignore requests to a subdomain of myapp.com with a glob patternxray_add_ignored(hostname='*.myapp.com')# ignore requests to /test-url and /other-test-urlxray_add_ignored(urls=['/test-path','/other-test-path'])# ignore requests to myapp.com for /test-urlxray_add_ignored(hostname='myapp.com',urls=['/test-url'])

If you use a subclass of httplib to make your requests, you can also filter on the class name that initiates the request. This must use the complete package name to do the match.

fromaws_xray_sdk.ext.httplibimportadd_ignoredasxray_add_ignored# ignore all requests made by botocorexray_add_ignored(subclass='botocore.awsrequest.AWSHTTPConnection')

License

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

Sours: https://pypi.org/project/aws-xray-sdk/

Ray sdk x

AWS X-Ray SDK for Node.js

Continuous Build

Screenshot of the AWS X-Ray console

Installing

The AWS X-Ray SDK for Node.js is compatible with Node.js version 10.x and later. There may be issues when running on the latest odd-numbered release of Node.js.

The latest stable version of the SDK is available from NPM. For local development, install the SDK in your project directory with npm.

Use the --save option to save the SDK as a dependency in your application's .

Documentation

This repository hosts all the packages we publish, which each have their own README. The Core package README covers all basic use cases of the main X-Ray SDK, including its use in Lambda. The developer guide provides in-depth guidance about using the AWS X-Ray service and SDKs. The API Reference provides guidance for using this SDK and module-level documentation.

CHANGELOG.md

Sample App

To get started with a functional web application instrumented with the X-Ray SDK, check out our sample app.

Getting Help

Use the following community resources for getting help with the SDK. 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 Node.js, we want to hear about it. Before opening a new issue, search the existing issues to see if others are also experiencing the issue. Include the version of the AWS X-Ray SDK for Node.js, Node.js runtime, and other dependencies if applicable. In addition, include the repro case when appropriate.

The GitHub issues are intended for bug reports and feature requests. For help and questions about using the AWS X-Ray SDK for Node.js, use the resources listed in the Getting Help section. Keeping the list of open issues lean helps us respond in a timely manner.

Contributing

We support and accept PRs from the community.

This monorepo hosts the following npm packages for the SDK:

Community contributions for new Middleware

If you'd like to add support for a new web framework by writing middleware for X-Ray, please do so by creating a new package within the directory. We are not accepting pull requests for first-party packages at this time, but will be more than happy to host them as community contributions. This means that AWS will:

  • Host them in this repository
  • Publish them to NPM
  • Consider them the officially recommended way of using X-Ray with that framework
  • Review & merge pull requests made against them by the community
  • Allow issues related to them on this repo for visibility to the community

AWS will not:

  • Provide first party support through AWS Forums, AWS customer support, etc for things like questions & debugging help
  • Actively develop on them (e.g. if we add a feature to the Express middleware, it will not necessarily be added to middleware in )

Testing from Source

This repo uses Lerna to manage multiple packages. To install Lerna as a CLI:

To install devDependencies and peerDependencies for all packages:

This repo has a combination of TypeScript and JavaScript source files. To transpile the TypeScript files for testing, run:

To run tests for all packages:

or go to each package and run as usual.

License

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

Sours: https://github.com/aws/aws-xray-sdk-node
AWS X-Ray for Serverless Applications - Serverless Monitoring

But in the middle of the presidential suite, the Prince was kneeling, and before him, sprawling on the floor, shuddering in convulsions of ecstasy, lay the beautiful Cinderella, reaching the. Height of bliss. The Prince Charming smiled with his cheerful good-natured smile, lifted the girl's body and gently carried it onto a wide bed. An hour later, naked and tired Cinderella was reclining on the shoulder of the handsome Prince, squeezing his manhood, which was gaining strength again, and at that moment there.

You will also be interested:

Involuntarily put his hand on her ass. There were no panties under the dress and I lowered my hand a little, wanting to raise the hem and check it more precisely. Auntie looked at me without changing position and asked if I thought it was right what I was going to do. Of course I do.

And the hand was already stroking her naked ass, penetrated to the pussy, began to stroke and fiddle with the vegetation around the labia.



341 342 343 344 345