Перейти к основному содержанию
Перейти к основному содержанию

Node.js

ClickStack использует стандарт OpenTelemetry для сбора телеметрических данных (логов, метрик, трейсов и исключений). Трейсы автоматически формируются за счёт автоматической инструментации, поэтому ручная инструментация не требуется, чтобы извлекать пользу из трассировки.

В этом руководстве рассматривается интеграция:

  • Логи
  • Метрики
  • Трейсы
  • Исключения

Начало работы

Установка пакета инструментирования HyperDX OpenTelemetry

Установите пакет ClickStack OpenTelemetry с помощью следующей команды.

npm install @hyperdx/node-opentelemetry 

Инициализация SDK

Чтобы инициализировать SDK, вам нужно вызвать функцию init в самом начале файла — точки входа вашего приложения.

const HyperDX = require('@hyperdx/node-opentelemetry');

HyperDX.init({
    apiKey: 'YOUR_INGESTION_API_KEY',
    service: 'my-service'
});

Это позволит автоматически собирать трейсы, метрики и логи из вашего Node.js-приложения.

Настройка сбора логов

По умолчанию логи console.* собираются автоматически. Если вы используете логгер такой, как winston или pino, вам необходимо добавить в него транспорт для отправки логов в ClickStack. Если вы используете другой тип логгера, свяжитесь с нами или изучите одну из наших платформенных интеграций, если это применимо (например, Kubernetes).

Если вы используете winston в качестве логгера, вам необходимо добавить в него следующий транспорт.

    import winston from 'winston';
    import * as HyperDX from '@hyperdx/node-opentelemetry';

    const logger = winston.createLogger({
      level: 'info',
      format: winston.format.json(),
      transports: [
        new winston.transports.Console(),
        HyperDX.getWinstonTransport('info', { // Send logs info and above
          detectResources: true,
        }),
      ],
    });

    export default logger;

Настройка сбора ошибок

SDK ClickStack может автоматически собирать необработанные исключения и ошибки в вашем приложении с полным стеком вызовов и контекстом кода.

Чтобы включить сбор, добавьте следующий код в конец middleware-обработчика ошибок вашего приложения или вручную фиксируйте исключения с помощью функции recordException.

const HyperDX = require('@hyperdx/node-opentelemetry');
HyperDX.init({
    apiKey: 'YOUR_INGESTION_API_KEY',
    service: 'my-service'
});
const app = express();

// Add your routes, etc.

// Add this after all routes,
// but before any and other error-handling middlewares are defined
HyperDX.setupExpressErrorHandler(app);

app.listen(3000);

Устранение неполадок

Если у вас возникают проблемы с SDK, вы можете включить подробное логирование, установив переменную окружения OTEL_LOG_LEVEL в значение debug.

export OTEL_LOG_LEVEL=debug

Расширенная конфигурация инструментирования

Сбор логов консоли

По умолчанию SDK ClickStack собирает логи консоли. Чтобы отключить это, установите для переменной окружения HDX_NODE_CONSOLE_CAPTURE значение 0.

export HDX_NODE_CONSOLE_CAPTURE=0

Attach user information or metadata

To easily tag all events related to a given attribute or identifier (ex. user id or email), you can call the setTraceAttributes function which will tag every log/span associated with the current trace after the call with the declared attributes. It's recommended to call this function as early as possible within a given request/trace (ex. as early in an Express middleware stack as possible).

This is a convenient way to ensure all logs/spans are automatically tagged with the right identifiers to be searched on later, instead of needing to manually tag and propagate identifiers yourself.

userId, userEmail, userName, and teamName will populate the sessions UI with the corresponding values, but can be omitted. Any other additional values can be specified and used to search for events.

import * as HyperDX from '@hyperdx/node-opentelemetry';

app.use((req, res, next) => {
  // Получить информацию о пользователе из запроса...

  // Присоединить информацию о пользователе к текущей трассировке
  HyperDX.setTraceAttributes({
    userId,
    userEmail,
  });

  next();
});

Make sure to enable beta mode by setting HDX_NODE_BETA_MODE environment variable to 1 or by passing betaMode: true to the init function to enable trace attributes.

export HDX_NODE_BETA_MODE=1

Google Cloud Run

If you're running your application on Google Cloud Run, Cloud Trace automatically injects sampling headers into incoming requests, currently restricting traces to be sampled at 0.1 requests per second for each instance.

The @hyperdx/node-opentelemetry package overwrites the sample rate to 1.0 by default.

To change this behavior, or to configure other OpenTelemetry installations, you can manually configure the environment variables OTEL_TRACES_SAMPLER=parentbased_always_on and OTEL_TRACES_SAMPLER_ARG=1 to achieve the same result.

To learn more, and to force tracing of specific requests, please refer to the Google Cloud Run documentation.

Auto-instrumented libraries

The following libraries will be automatically instrumented (traced) by the SDK:

Alternative installation

Run the Application with ClickStack OpenTelemetry CLI

Alternatively, you can auto-instrument your application without any code changes by using the opentelemetry-instrument CLI or using the Node.js --require flag. The CLI installation exposes a wider range of auto-instrumented libraries and frameworks.

HYPERDX_API_KEY='<YOUR_INGESTION_KEY>' OTEL_SERVICE_NAME='<YOUR_APP_NAME>' npx opentelemetry-instrument index.js

The OTEL_SERVICE_NAME environment variable is used to identify your service in the HyperDX app, it can be any name you want.

Enabling exception capturing

To enable uncaught exception capturing, you'll need to set the HDX_NODE_EXPERIMENTAL_EXCEPTION_CAPTURE environment variable to 1.

HDX_NODE_EXPERIMENTAL_EXCEPTION_CAPTURE=1

После этого, чтобы автоматически перехватывать исключения в Express или Koa либо обрабатывать их вручную, следуйте инструкциям в разделе Настройка сбора ошибок выше.

Автоматически инструментируемые библиотеки

Следующие библиотеки будут автоматически инструментированы (с включением трассировки) с помощью описанных выше методов установки: