AWS-XRay
view release on metacpan or search on metacpan
lib/AWS/XRay.pm view on Meta::CPAN
if ($header =~ /Sampled=([^;]+)/) {
$sampled = $1;
}
return ($trace_id, $segment_id, $sampled);
}
sub add_capture {
my ($class, $package, @methods) = @_;
no warnings 'redefine';
no strict 'refs';
for my $method (@methods) {
my $orig = $package->can($method) or next;
*{"${package}::${method}"} = sub {
my @args = @_;
capture(
$package,
sub {
my $segment = shift;
$segment->{metadata}->{method} = $method;
$segment->{metadata}->{package} = $package;
$orig->(@args);
},
);
};
}
}
if ($ENV{LAMBDA_TASK_ROOT}) {
# AWS::XRay is loaded in AWS Lambda worker.
# notify the Lambda Runtime that initialization is complete.
unless (mkdir '/tmp/.aws-xray') {
# ignore the error if the directory is already exits or other process created it.
my $err = $!;
unless (-d '/tmp/.aws-xray') {
warn "failed to make directory: $err";
}
}
open my $fh, '>', '/tmp/.aws-xray/initialized' or warn "failed to create file: $!";
close $fh;
utime undef, undef, '/tmp/.aws-xray/initialized' or warn "failed to touch file: $!";
# patch the capture
no warnings 'redefine';
no strict 'refs';
my $org = \&capture;
*capture = sub {
my ($trace_id, $segment_id, $sampled) = parse_trace_header($ENV{_X_AMZN_TRACE_ID});
local $AWS::XRay::SAMPLED = $sampled // $SAMPLER->();
local $AWS::XRay::ENABLED = $AWS::XRay::SAMPLED;
local ($AWS::XRay::TRACE_ID, $AWS::XRay::SEGMENT_ID) = ($trace_id, $segment_id);
local *capture = $org;
local *trace = $org;
capture(@_);
};
*trace = \&capture;
}
1;
__END__
=encoding utf-8
=head1 NAME
AWS::XRay - AWS X-Ray tracing library
=head1 SYNOPSIS
use AWS::XRay qw/ capture /;
capture "myApp", sub {
capture "remote", sub {
# do something ...
capture "nested", sub {
# ...
};
};
capture "myHTTP", sub {
my $segment = shift;
# ...
$segment->{http} = { # modify segment document
request => {
method => "GET",
url => "http://localhost/",
},
response => {
status => 200,
},
};
};
};
my $header;
capture "source", sub {
my $segment = shift;
$header = $segment->trace_header;
};
capture_from $header, "dest", sub {
my $segment = shift; # is a child of "source" segment
# ...
};
=head1 DESCRIPTION
AWS::XRay is a tracing library with AWS X-Ray.
AWS::XRay sends segment data to L<AWS X-Ray Daemon|https://docs.aws.amazon.com/xray/latest/devguide/xray-daemon.html>.
=head1 FUNCTIONS
=head2 new_trace_id
Generate a Trace ID. (e.g. "1-581cf771-a006649127e371903a2de979")
L<Document|https://docs.aws.amazon.com/xray/latest/devguide/xray-api-sendingdata.html#xray-api-traceids>
=head2 capture($name, $code)
capture() executes $code->($segment) and send the segment document to X-Ray daemon.
$segment is a AWS::XRay::Segment object.
( run in 1.022 second using v1.01-cache-2.11-cpan-39bf76dae61 )