Skip to content

feat(node): Move default option handling from init to NodeClient #16353

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ export {
isVueViewModel,
} from './utils-hoist/is';
export { isBrowser } from './utils-hoist/isBrowser';
export { CONSOLE_LEVELS, consoleSandbox, logger, originalConsoleMethods } from './utils-hoist/logger';
export { CONSOLE_LEVELS, consoleSandbox, logger, originalConsoleMethods, enableLogger } from './utils-hoist/logger';
export type { Logger } from './utils-hoist/logger';
export {
addContextToFrame,
Expand Down
22 changes: 5 additions & 17 deletions packages/core/src/sdk.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import type { Client } from './client';
import { getCurrentScope } from './currentScopes';
import { DEBUG_BUILD } from './debug-build';
import type { ClientOptions } from './types-hoist/options';
import { consoleSandbox, logger } from './utils-hoist/logger';
import { enableLogger } from './utils-hoist/logger';

/** A class object that can instantiate Client objects. */
export type ClientClass<F extends Client, O extends ClientOptions> = new (options: O) => F;
Expand All @@ -14,25 +13,14 @@ export type ClientClass<F extends Client, O extends ClientOptions> = new (option
* @param clientClass The client class to instantiate.
* @param options Options to pass to the client.
*/
export function initAndBind<F extends Client, O extends ClientOptions>(
clientClass: ClientClass<F, O>,
options: O,
): Client {
if (options.debug === true) {
if (DEBUG_BUILD) {
logger.enable();
} else {
// use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');
});
}
export function initAndBind<F extends Client, O extends ClientOptions>(ClientClass: ClientClass<F, O>, options: O): F {
if (options.debug) {
enableLogger();
}
const scope = getCurrentScope();
scope.update(options.initialScope);

const client = new clientClass(options);
const client = new ClientClass(options);
setCurrentClient(client);
client.init();
return client;
Expand Down
13 changes: 13 additions & 0 deletions packages/core/src/utils-hoist/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,16 @@ function makeLogger(): Logger {
* The logger is a singleton on the carrier, to ensure that a consistent logger is used throughout the SDK.
*/
export const logger = getGlobalSingleton('logger', makeLogger);

/** Enables the logger, or log a warning if DEBUG_BUILD is false. */
export function enableLogger(): void {
if (DEBUG_BUILD) {
logger.enable();
} else {
// use `console.warn` rather than `logger.warn` since non-debug bundles have all `logger.x` statements stripped
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');
});
}
}
72 changes: 59 additions & 13 deletions packages/node/src/sdk/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@ import type { Tracer } from '@opentelemetry/api';
import { trace } from '@opentelemetry/api';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import type { BasicTracerProvider } from '@opentelemetry/sdk-trace-base';
import type { DynamicSamplingContext, Scope, ServerRuntimeClientOptions, TraceContext } from '@sentry/core';
import type { DynamicSamplingContext, Scope, TraceContext } from '@sentry/core';
import { _INTERNAL_flushLogsBuffer, applySdkMetadata, logger, SDK_VERSION, ServerRuntimeClient } from '@sentry/core';
import { getTraceContextForScope } from '@sentry/opentelemetry';
import {
enhanceDscWithOpenTelemetryRootSpanName,
getTraceContextForScope,
setupEventContextTrace,
} from '@sentry/opentelemetry';
import { isMainThread, threadId } from 'worker_threads';
import { DEBUG_BUILD } from '../debug-build';
import type { NodeClientOptions } from '../types';
import { isCjs } from '../utils/commonjs';
import { envToBool } from '../utils/envToBool';
import { getSentryRelease } from './api';

const DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS = 60_000; // 60s was chosen arbitrarily

Expand All @@ -21,15 +28,9 @@ export class NodeClient extends ServerRuntimeClient<NodeClientOptions> {
private _logOnExitFlushListener: (() => void) | undefined;

public constructor(options: NodeClientOptions) {
const serverName = options.serverName || global.process.env.SENTRY_NAME || os.hostname();
const clientOptions: ServerRuntimeClientOptions = {
...options,
platform: 'node',
runtime: { name: 'node', version: global.process.version },
serverName,
};

if (options.openTelemetryInstrumentations) {
const clientOptions = applyDefaultOptions(options);

if (clientOptions.openTelemetryInstrumentations) {
registerInstrumentations({
instrumentations: options.openTelemetryInstrumentations,
});
Expand All @@ -40,25 +41,31 @@ export class NodeClient extends ServerRuntimeClient<NodeClientOptions> {
logger.log(
`Initializing Sentry: process: ${process.pid}, thread: ${isMainThread ? 'main' : `worker-${threadId}`}.`,
);
logger.log(`Running in ${isCjs() ? 'CommonJS' : 'ESM'} mode.`);

super(clientOptions);

this.startClientReportTracking();

if (this.getOptions()._experiments?.enableLogs) {
this._logOnExitFlushListener = () => {
_INTERNAL_flushLogsBuffer(this);
};

if (serverName) {
if (clientOptions.serverName) {
this.on('beforeCaptureLog', log => {
log.attributes = {
...log.attributes,
'server.address': serverName,
'server.address': clientOptions.serverName,
};
});
}

process.on('beforeExit', this._logOnExitFlushListener);
}

enhanceDscWithOpenTelemetryRootSpanName(this);
setupEventContextTrace(this);
}

/** Get the OTEL tracer. */
Expand Down Expand Up @@ -154,3 +161,42 @@ export class NodeClient extends ServerRuntimeClient<NodeClientOptions> {
return getTraceContextForScope(this, scope);
}
}

function applyDefaultOptions<T extends Partial<NodeClientOptions>>(options: T): T {
const release = options.release ?? getSentryRelease();
const spotlight =
options.spotlight ?? envToBool(process.env.SENTRY_SPOTLIGHT, { strict: true }) ?? process.env.SENTRY_SPOTLIGHT;
const tracesSampleRate = getTracesSampleRate(options.tracesSampleRate);
const serverName = options.serverName || global.process.env.SENTRY_NAME || os.hostname();

return {
platform: 'node',
runtime: { name: 'node', version: global.process.version },
serverName,
...options,
dsn: options.dsn ?? process.env.SENTRY_DSN,
environment: options.environment ?? process.env.SENTRY_ENVIRONMENT,
sendClientReports: options.sendClientReports ?? true,
release,
tracesSampleRate,
spotlight,
debug: envToBool(options.debug ?? process.env.SENTRY_DEBUG),
};
}

/**
* Tries to get a `tracesSampleRate`, possibly extracted from the environment variables.
*/
export function getTracesSampleRate(tracesSampleRate: NodeClientOptions['tracesSampleRate']): number | undefined {
if (tracesSampleRate !== undefined) {
return tracesSampleRate;
}

const sampleRateFromEnv = process.env.SENTRY_TRACES_SAMPLE_RATE;
if (!sampleRateFromEnv) {
return undefined;
}

const parsed = parseFloat(sampleRateFromEnv);
return isFinite(parsed) ? parsed : undefined;
}
Loading
Loading