# @aspecto/opentelemetry

> Aspecto auto instrumentation for nodejs applications

Latest version **0.2.0** (published 2024-05-21) · Apache-2.0 license · 0 weekly downloads

## Install

```sh
npm install @aspecto/opentelemetry
pnpm add @aspecto/opentelemetry
yarn add @aspecto/opentelemetry
bun add @aspecto/opentelemetry
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.2.0 |
| Published | 2024-05-21 |
| First published | 2020-06-23 |
| Weekly downloads | 0 |
| License | Apache-2.0 |
| TypeScript types | bundled |
| Module format | CommonJS |
| Node | >=14.0.0 |
| Dependencies | 56 |
| Unpacked size | 410.2 KB |
| Known vulnerabilities | 0 (+2 in 2 direct dependencies) |
| Install scripts | no |
| Author | Aspecto.io |
| Maintainers | habmic, amir.aspecto, aspecto-release-bot, andriy-aspecto, yanivd |
| Keywords | opentelemetry |

## Links

- npm: https://www.npmjs.com/package/@aspecto/opentelemetry
- Repository: https://github.com/aspecto-io/aspecto-opentelemetry-js
- Homepage: https://docs.aspecto.io/v1/
- Issues: https://github.com/aspecto-io/aspecto-opentelemetry-js/issues
- npm.io page: https://npm.io/package/@aspecto/opentelemetry

## Dependencies (56)

- [uuid](https://npm.io/package/uuid.md) ^8.3.1
- [debug](https://npm.io/package/debug.md) ^4.3.1
- [lodash](https://npm.io/package/lodash.md) ^4.17.21
- [shimmer](https://npm.io/package/shimmer.md) 1.2.1
- [is-promise](https://npm.io/package/is-promise.md) ^4.0.0
- [object-sizeof](https://npm.io/package/object-sizeof.md) 1.6.1
- [@types/aws-lambda](https://npm.io/package/@types/aws-lambda.md) ^8.10.119
- [@opentelemetry/api](https://npm.io/package/@opentelemetry/api.md) ^1.8.0
- [@opentelemetry/core](https://npm.io/package/@opentelemetry/core.md) ^1.24.1
- [@aspecto/sampling-rules](https://npm.io/package/@aspecto/sampling-rules.md) 0.0.7
- [@opentelemetry/resources](https://npm.io/package/@opentelemetry/resources.md) 1.24.1
- [@aspecto/opentelemetry-base](https://npm.io/package/@aspecto/opentelemetry-base.md) ^0.2.0
- [@aspecto/opentelemetry-diag](https://npm.io/package/@aspecto/opentelemetry-diag.md) ^0.2.0
- [@opentelemetry/propagator-b3](https://npm.io/package/@opentelemetry/propagator-b3.md) 1.24.1
- [@aspecto/opentelemetry-config](https://npm.io/package/@aspecto/opentelemetry-config.md) ^0.2.0
- [@opentelemetry/sdk-trace-base](https://npm.io/package/@opentelemetry/sdk-trace-base.md) 1.24.1
- [@opentelemetry/sdk-trace-node](https://npm.io/package/@opentelemetry/sdk-trace-node.md) 1.24.1
- [@aspecto/opentelemetry-sampler](https://npm.io/package/@aspecto/opentelemetry-sampler.md) ^0.2.0
- [@opentelemetry/exporter-zipkin](https://npm.io/package/@opentelemetry/exporter-zipkin.md) 1.24.1
- [@opentelemetry/instrumentation](https://npm.io/package/@opentelemetry/instrumentation.md) ^0.51.1
- [@opentelemetry/propagation-utils](https://npm.io/package/@opentelemetry/propagation-utils.md) 0.30.9
- [@opentelemetry/instrumentation-pg](https://npm.io/package/@opentelemetry/instrumentation-pg.md) 0.41.0
- [@opentelemetry/context-async-hooks](https://npm.io/package/@opentelemetry/context-async-hooks.md) ^1.24.1
- [opentelemetry-propagator-selective](https://npm.io/package/opentelemetry-propagator-selective.md) 0.31.0
- [@opentelemetry/instrumentation-http](https://npm.io/package/@opentelemetry/instrumentation-http.md) 0.51.1
- [@opentelemetry/instrumentation-pino](https://npm.io/package/@opentelemetry/instrumentation-pino.md) 0.39.0
- [@opentelemetry/semantic-conventions](https://npm.io/package/@opentelemetry/semantic-conventions.md) ^1.24.1
- [opentelemetry-instrumentation-neo4j](https://npm.io/package/opentelemetry-instrumentation-neo4j.md) 0.41.0
- [opentelemetry-resource-detector-git](https://npm.io/package/opentelemetry-resource-detector-git.md) 0.30.0
- [@opentelemetry/instrumentation-mysql](https://npm.io/package/@opentelemetry/instrumentation-mysql.md) 0.38.1
- [@opentelemetry/instrumentation-redis](https://npm.io/package/@opentelemetry/instrumentation-redis.md) 0.39.1
- [@opentelemetry/instrumentation-bunyan](https://npm.io/package/@opentelemetry/instrumentation-bunyan.md) 0.38.0
- [@opentelemetry/instrumentation-mysql2](https://npm.io/package/@opentelemetry/instrumentation-mysql2.md) 0.38.1
- [opentelemetry-instrumentation-express](https://npm.io/package/opentelemetry-instrumentation-express.md) 0.41.0
- [opentelemetry-instrumentation-kafkajs](https://npm.io/package/opentelemetry-instrumentation-kafkajs.md) 0.41.0
- [opentelemetry-instrumentation-typeorm](https://npm.io/package/opentelemetry-instrumentation-typeorm.md) 0.41.0
- [@opentelemetry/instrumentation-amqplib](https://npm.io/package/@opentelemetry/instrumentation-amqplib.md) 0.37.0
- [@opentelemetry/instrumentation-aws-sdk](https://npm.io/package/@opentelemetry/instrumentation-aws-sdk.md) 0.41.0
- [@opentelemetry/instrumentation-ioredis](https://npm.io/package/@opentelemetry/instrumentation-ioredis.md) 0.40.0
- [@opentelemetry/instrumentation-redis-4](https://npm.io/package/@opentelemetry/instrumentation-redis-4.md) 0.39.0
- [@opentelemetry/instrumentation-tedious](https://npm.io/package/@opentelemetry/instrumentation-tedious.md) 0.10.1
- [@opentelemetry/instrumentation-winston](https://npm.io/package/@opentelemetry/instrumentation-winston.md) 0.37.0
- [@opentelemetry/exporter-trace-otlp-http](https://npm.io/package/@opentelemetry/exporter-trace-otlp-http.md) 0.51.1
- [@opentelemetry/instrumentation-mongoose](https://npm.io/package/@opentelemetry/instrumentation-mongoose.md) 0.38.1
- [opentelemetry-instrumentation-sequelize](https://npm.io/package/opentelemetry-instrumentation-sequelize.md) 0.41.0
- [opentelemetry-resource-detector-service](https://npm.io/package/opentelemetry-resource-detector-service.md) 0.30.0
- [@opentelemetry/exporter-trace-otlp-proto](https://npm.io/package/@opentelemetry/exporter-trace-otlp-proto.md) 0.51.1
- [@opentelemetry/instrumentation-socket.io](https://npm.io/package/@opentelemetry/instrumentation-socket.io.md) 0.39.0
- [opentelemetry-instrumentation-node-cache](https://npm.io/package/opentelemetry-instrumentation-node-cache.md) 0.41.0
- [opentelemetry-resource-detector-sync-api](https://npm.io/package/opentelemetry-resource-detector-sync-api.md) 0.30.0
- [@opentelemetry/instrumentation-aws-lambda](https://npm.io/package/@opentelemetry/instrumentation-aws-lambda.md) 0.41.1
- [@opentelemetry/instrumentation-nestjs-core](https://npm.io/package/@opentelemetry/instrumentation-nestjs-core.md) 0.37.1
- [opentelemetry-resource-detector-deployment](https://npm.io/package/opentelemetry-resource-detector-deployment.md) 0.30.0
- [@opentelemetry/instrumentation-lru-memoizer](https://npm.io/package/@opentelemetry/instrumentation-lru-memoizer.md) 0.37.0
- [opentelemetry-instrumentation-elasticsearch](https://npm.io/package/opentelemetry-instrumentation-elasticsearch.md) 0.41.0
- [@aspecto/opentelemetry-instrumentation-mongodb](https://npm.io/package/@aspecto/opentelemetry-instrumentation-mongodb.md) ^0.2.0

## Recent versions

- 0.2.0 (latest) — 2024-05-21
- 0.0.0-2024-05-21--09-06 (alpha) — 2024-05-21
- 0.0.115-dev.0 (dev) — 2021-04-27
- 0.0.114-alpha.4 (canary) — 2021-04-26
- 0.0.0-2024-05-16--14-39 — 2024-05-16
- 0.1.0 — 2023-10-17
- 0.0.0-2023-10-17--12-24 — 2023-10-17
- 0.0.0-2023-10-17--12-07 — 2023-10-17
- 0.0.0-2023-10-17--11-48 — 2023-10-17
- 0.0.142 — 2023-09-21
- 0.0.0-2023-07-30--08-42 — 2023-07-30
- 0.0.0-2023-07-27--11-15 — 2023-07-27
- 0.0.140 — 2023-03-01
- 0.0.0-2023-03-01--13-22 — 2023-03-01
- 0.0.0-2023-02-28--15-21 — 2023-02-28
- … 201 more at https://npm.io/package/@aspecto/opentelemetry/versions

## README

# Aspecto OpenTelemetry SDK

Aspecto is an observability platform, powered by OpenTelemetry, that brings R&D teams complete visibility into every interaction, performance issue, and error happening within their distributed services.

* [Install](#install)
* [Usage](#usage)
* [Configuration](#configuration)
* [Send Spans Manually](#send-spans-manually)
* [Add span attributes manually](#add-span-attributes-manually)
* [Correlate Logs with Traces](#correlate-logs-with-traces)
* [Live Stream Traces](#live-stream-traces)
    * [Connected Mode](#connected-mode)
* [FaaS](#faas)
    * [AWS Lambda](#aws-lambda)
    * [Google Cloud Function](#google-cloud-function)

## Install
```sh
npm install @aspecto/opentelemetry
```

Supported node version: >= 14

## Usage

In the root folder create an `aspecto.json` file with the content `{"aspectoAuth" : "-- token goes here --"}`. 

You can get your token from [here](https://app.aspecto.io/app/integration)

Add this call at the top of your app entry point:

```js
require('@aspecto/opentelemetry')();

// the rest of your main file requires
```

See below for more [configuration options](#configuration)

## Configuration

You can configure the package via one or more of the following:
- `options` variable. for example: `require('@aspecto/opentelemetry')({optionName: optionValue});`  
This enables setting config options dynamically.
- Environment variables
- Add `aspecto.json` configuration file to the root directory, next to service's `package.json` file

Values are evaluated in the following priority:
1) `options` object
2) environment variables
3) config file
4) default values

| Option Name | Environment Variable | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `disableAspecto` | `DISABLE_ASPECTO` |  boolean | `false` | Disable aspecto |
| `env` | `NODE_ENV` | string | - | Set environment name manually |
| `aspectoAuth` | `ASPECTO_AUTH` | UUID | - | Set [Aspecto token](https://app.aspecto.io/app/integration/api-key) from code instead of using `aspecto.json` |
| `serviceName` | `OTEL_SERVICE_NAME` | string | `name` key in `package.json` | Set serviceName manually instead of reading it from `package.json`. For example: a service that runs in multiple "modes" |
| `serviceVersion` | `OTEL_SERVICE_VERSION` | string | `version` key in `package.json` | Set serviceVersion manually instead of reading it from `package.json` |
| `samplingRatio` | `ASPECTO_SAMPLING_RATIO` | number | `1.0` | How many of the traces starting in this service should be sampled. Set to number in range [0.0, 1.0] where `0.0` is no sampling, and `1.0` is sample all. [Specific rules](https://docs.aspecto.io/v1/settings/sampling-rules) set via aspecto app takes precedence |
| `requireConfigForTraces` | `ASPECTO_REQUIRE_CONFIG_FOR_TRACES` | boolean | `false` | When `true`, the SDK will not trace anything until remote sampling configuration arrives (few hundreds ms). Can be used to enforce sampling configuration is always applied, with the cost of losing traces generated during service startup. |
| `logger` | - | logger interface | - | Logger to be used in this tracing library. Common use for debugging `logger: console` |
| `collectPayloads` | `ASPECTO_COLLECT_PAYLOADS` | boolean | `true` | Should Aspecto SDK collect payloads of operations |
| `otlpCollectorEndpoint` | OTEL_EXPORTER_OTLP_TRACES_ENDPOINT | `string` | `https://otelcol-fast.aspecto.io/v1/trace` | Target URL to which the OTLP http exporter is going to send spans |
| `exportBatchSize` | `ASPECTO_EXPORT_BATCH_SIZE` | number | `100` | How many spans to batch in a single export to the collector |
| `exportBatchTimeoutMs` | `ASPECTO_EXPORT_BATCH_TIMEOUT_MS` | number | `1000` (1s) | Maximum time in ms for batching spans before sending to collector |
| `writeSystemLogs` | - | boolean | `false` | If `true`, emit all log messages from Opentelemetry SDK to supplied logger if present, or to console if missing |
| `customZipkinEndpoint` | - | URL |  | Send all traces to additional Zipkin server for debug |
| `sqsExtractContextPropagationFromPayload` | `ASPECTO_SQS_EXTRACT_CONTEXT_PROPAGATION_FROM_PAYLOAD` | boolean | `true` | For aws-sdk instrumentation. Should be true when the service receiveMessages from SQS which is subscribed to SNS and subscription configured with "Raw message delivery": Disabled. Setting to `false` is a bit more performant as it turns off JSON parse on message payload |
| `extractB3Context` | `ASPECTO_EXTRACT_B3_CONTEXT` | boolean | `false` | Set to `true` when the service receives requests from another instrumented component that propagate context via B3 protocol multi or single header. For example: Envoy Proxy, Ambassador and Istio |
| `injectB3ContextSingleHeader` | `ASPECTO_INJECT_B3_CONTEXT_SINGLE_HEADER` | boolean | `false` | Set to `true` when the service send traffic to another instrumented component that propagate context via B3 **single header** protocol |
| `injectB3ContextMultiHeader` | `ASPECTO_INJECT_B3_CONTEXT_MULTI_HEADER` | boolean | `false` | Set to `true` when the service send traffic to another instrumented component that propagate context via B3 **multi header** protocol. For example: Envoy Proxy, Istio |

## Send Spans Manually
### Background
"Span" is the name of the data structure representing an interesting operation in your app.  
Aspecto will automatically collect spans for operations created by popular packages that perform IO (such as http, messaging systems, databases, etc).  
Manual spans are used if you need to trace an operation in a code you wrote, or when using a package that does not provide an automatic tracing. 
### Example

To create a Manual Span for a function run, you need to wrap it in a trace call like this:
```js
import { trace } from '@aspecto/opentelemetry'; // ES import
const { trace } = require('@aspecto/opentelemetry'); // CommonJS require

trace(
    // All options are optional
    {
        name: '** optional name for the operation **',
        metadata: {
            'metadata.key.for.the.operation': 'you can attach custom metadata to the operation',
        },
        type: 'Type of Operation',
    },
    () => {
        // your code which you want to trace
    }
);
```

## Add span attributes manually
You can add attributes to your spans for more visibility.  
Attributes can be added to a span at any time before the span is finished:

```js
import { setAttribute, setAttributes } from '@aspecto/opentelemetry';

// add a single attribute
const result = setAttribute('foo', 'bar');

// add multiple attributes
const result = setAttributes({ foo: 'bar' });

// result will be true in case of success
```

(*) All keys will get a prefix of 'aspecto.extra'.


## Correlate Logs with Traces
A common use case for the Trace Search tool is to see the related trace while inspecting a log event.  
To do this, you must attach an active `traceId` to your logs.

### Example
Use the `getContext` method, exposed from our package, to attach traceId to your logs:
```js
const { getContext } = require('@aspecto/opentelemetry');

console.log('Something happened!', { traceId: getContext().traceId })});
```

## Live Stream Traces

Live Stream Traces captures all payloads and traces for a specific host/instance.
You can access it by clicking the link from the service output:

```
=====================================================================================================================================
|                                                                                                                                   |
| 🕵️‍♀️ See the live stream tracing at https://app.aspecto.io/app/live-stream-traces/sessions?instanceId=14243e72-14dc-4255-87af-ef846b247578   |
|                                                                                                                                   |
=====================================================================================================================================
```

You only need to click the link once to see traces from all the microservices, that are running on your environment.
Also this link is valid for a limited period of time (couple of days, but it may change in the future).
If you don't see trace from some microservice (or none of them), please click the newly-generated link.
## FaaS

### AWS Lambda

Aspecto supports instrumenting AWS lambdas.  
To do so, set up Aspecto as you'd usually do, and extract the returned `lambda` utility:
```js
const { lambda } = require('@aspecto/opentelemetry')();
```
Next, wrap your function handler definition with the returned utility.

Example:
```js
// Before
module.exports.myCallbackHandler = (event, context, callback) => { ... };
module.exports.myAsyncHandler = async (event, context) => { ... };

// After
module.exports.myCallbackHandler = lambda((event, context, callback) => { ... });
module.exports.myAsyncHandler = lambda(async (event, context) => { ... });
```

Notice: if your lambda is not deployed with a `package.json` file, make sure to provide the `serviceName` option when initializing Aspecto.

### Google Cloud Function

Aspecto supports instrumenting GCF with **http trigger**.  
To do so, set up Aspecto as you'd usually do, and extract the `gcf` utility:
```js
const { gcf } = require('@aspecto/opentelemetry')();
```
Next, wrap your function handler definition with the returned utility.
Example:
```js
// Before
exports.myEndpoint = (req, res) => { ... };

// After
exports.myEndpoint = gcf((req, res) => { ... });
```

### Test Frameworks

#### Mocha
To instrument your test with aspecto using `mocha` version 8.0.0 and above, register [mocha plugin](https://mochajs.org/#root-hook-plugins) as instructed below.
In this mode, token (and other configuration) can be set only via [`aspecto.json` config file or environment variables](#configuration).

##### With CLI
```bash
mocha --require @aspecto/opentelemetry/mocha
```

##### With Mocha Config in package.json
```js
  "mocha": {
    "require": [
      "@aspecto/opentelemetry/mocha"
    ]
  }
```

##### Config File
```js
{
    "require": [
        "@aspecto/opentelemetry/mocha"
    ]
}
```

---
_Source: https://npm.io/package/@aspecto/opentelemetry · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
