Skip to content

feat(core): Add consoleLoggingIntegration for logs #15955

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

Merged
merged 3 commits into from
Apr 3, 2025
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;

Sentry.init({
dsn: 'https://[email protected]/1337',
_experiments: {
enableLogs: true,
},
integrations: [Sentry.consoleLoggingIntegration()],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
console.trace('console.trace', 123, false);
console.debug('console.debug', 123, false);
console.log('console.log', 123, false);
console.info('console.info', 123, false);
console.warn('console.warn', 123, false);
console.error('console.error', 123, false);
console.assert(false, 'console.assert', 123, false);

console.log('');

Sentry.flush();
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { expect } from '@playwright/test';
import type { OtelLogEnvelope } from '@sentry/core';

import { sentryTest } from '../../../../utils/fixtures';
import { getFirstSentryEnvelopeRequest, properFullEnvelopeRequestParser } from '../../../../utils/helpers';

sentryTest('should capture console object calls', async ({ getLocalTestUrl, page }) => {
const bundle = process.env.PW_BUNDLE || '';
// Only run this for npm package exports
if (bundle.startsWith('bundle') || bundle.startsWith('loader')) {
sentryTest.skip();
}

const url = await getLocalTestUrl({ testDir: __dirname });

const event = await getFirstSentryEnvelopeRequest<OtelLogEnvelope>(page, url, properFullEnvelopeRequestParser);
const envelopeItems = event[1];

expect(envelopeItems[0]).toEqual([
{
type: 'otel_log',
},
{
severityText: 'trace',
body: { stringValue: 'console.trace 123 false' },
attributes: [],
timeUnixNano: expect.any(String),
traceId: expect.any(String),
severityNumber: 1,
},
]);

expect(envelopeItems[1]).toEqual([
{
type: 'otel_log',
},
{
severityText: 'debug',
body: { stringValue: 'console.debug 123 false' },
attributes: [],
timeUnixNano: expect.any(String),
traceId: expect.any(String),
severityNumber: 5,
},
]);

expect(envelopeItems[2]).toEqual([
{
type: 'otel_log',
},
{
severityText: 'info',
body: { stringValue: 'console.log 123 false' },
attributes: [],
timeUnixNano: expect.any(String),
traceId: expect.any(String),
severityNumber: 10,
},
]);

expect(envelopeItems[3]).toEqual([
{
type: 'otel_log',
},
{
severityText: 'info',
body: { stringValue: 'console.info 123 false' },
attributes: [],
timeUnixNano: expect.any(String),
traceId: expect.any(String),
severityNumber: 9,
},
]);

expect(envelopeItems[4]).toEqual([
{
type: 'otel_log',
},
{
severityText: 'warn',
body: { stringValue: 'console.warn 123 false' },
attributes: [],
timeUnixNano: expect.any(String),
traceId: expect.any(String),
severityNumber: 13,
},
]);

expect(envelopeItems[5]).toEqual([
{
type: 'otel_log',
},
{
severityText: 'error',
body: { stringValue: 'console.error 123 false' },
attributes: [],
timeUnixNano: expect.any(String),
traceId: expect.any(String),
severityNumber: 17,
},
]);

expect(envelopeItems[6]).toEqual([
{
type: 'otel_log',
},
{
severityText: 'error',
body: { stringValue: 'Assertion failed: console.assert 123 false' },
attributes: [],
timeUnixNano: expect.any(String),
traceId: expect.any(String),
severityNumber: 17,
},
]);
});
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { expect } from '@playwright/test';
import type { OtelLogEnvelope } from '@sentry/core';

import { sentryTest } from '../../../utils/fixtures';
import { getFirstSentryEnvelopeRequest, properFullEnvelopeRequestParser } from '../../../utils/helpers';
import { sentryTest } from '../../../../utils/fixtures';
import { getFirstSentryEnvelopeRequest, properFullEnvelopeRequestParser } from '../../../../utils/helpers';

sentryTest('should capture all logging methods', async ({ getLocalTestUrl, page }) => {
const bundle = process.env.PW_BUNDLE || '';
Expand Down
1 change: 1 addition & 0 deletions packages/astro/src/index.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ export {
zodErrorsIntegration,
profiler,
logger,
consoleLoggingIntegration,
} from '@sentry/node';

export { init } from './server/sdk';
Expand Down
1 change: 1 addition & 0 deletions packages/aws-serverless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export {
amqplibIntegration,
vercelAIIntegration,
logger,
consoleLoggingIntegration,
} from '@sentry/node';

export {
Expand Down
1 change: 1 addition & 0 deletions packages/browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export {
extraErrorDataIntegration,
rewriteFramesIntegration,
captureFeedback,
consoleLoggingIntegration,
} from '@sentry/core';

export { replayIntegration, getReplay } from '@sentry-internal/replay';
Expand Down
1 change: 1 addition & 0 deletions packages/bun/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ export {
amqplibIntegration,
vercelAIIntegration,
logger,
consoleLoggingIntegration,
} from '@sentry/node';

export {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export { trpcMiddleware } from './trpc';
export { captureFeedback } from './feedback';
export type { ReportDialogOptions } from './report-dialog';
export { _INTERNAL_captureLog, _INTERNAL_flushLogsBuffer } from './logs/exports';
export { consoleLoggingIntegration } from './logs/console-integration';

// TODO: Make this structure pretty again and don't do "export *"
export * from './utils-hoist/index';
Expand Down
82 changes: 82 additions & 0 deletions packages/core/src/logs/console-integration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { getClient } from '../currentScopes';
import { DEBUG_BUILD } from '../debug-build';
import { defineIntegration } from '../integration';
import type { ConsoleLevel, IntegrationFn } from '../types-hoist';
import { CONSOLE_LEVELS, GLOBAL_OBJ, addConsoleInstrumentationHandler, logger, safeJoin } from '../utils-hoist';
import { _INTERNAL_captureLog } from './exports';

interface CaptureConsoleOptions {
levels: ConsoleLevel[];
}

type GlobalObjectWithUtil = typeof GLOBAL_OBJ & {
util: {
format: (...args: unknown[]) => string;
};
};

const INTEGRATION_NAME = 'ConsoleLogs';

const _consoleLoggingIntegration = ((options: Partial<CaptureConsoleOptions> = {}) => {
const levels = options.levels || CONSOLE_LEVELS;

return {
name: INTEGRATION_NAME,
setup(client) {
if (!client.getOptions()._experiments?.enableLogs) {
DEBUG_BUILD && logger.warn('`_experiments.enableLogs` is not enabled, ConsoleLogs integration disabled');
return;
}

addConsoleInstrumentationHandler(({ args, level }) => {
if (getClient() !== client || !levels.includes(level)) {
return;
}

if (level === 'assert') {
if (!args[0]) {
const followingArgs = args.slice(1);
const message =
followingArgs.length > 0 ? `Assertion failed: ${formatConsoleArgs(followingArgs)}` : 'Assertion failed';
_INTERNAL_captureLog({ level: 'error', message });
}
return;
}

const isLevelLog = level === 'log';
_INTERNAL_captureLog({
level: isLevelLog ? 'info' : level,
message: formatConsoleArgs(args),
severityNumber: isLevelLog ? 10 : undefined,
});
});
},
};
}) satisfies IntegrationFn;

/**
* Captures calls to the `console` API as logs in Sentry. Requires `_experiments.enableLogs` to be enabled.
*
* @experimental This feature is experimental and may be changed or removed in future versions.
*
* By default the integration instruments `console.debug`, `console.info`, `console.warn`, `console.error`,
* `console.log`, `console.trace`, and `console.assert`. You can use the `levels` option to customize which
* levels are captured.
*
* @example
*
* ```ts
* import * as Sentry from '@sentry/browser';
*
* Sentry.init({
* integrations: [Sentry.consoleLoggingIntegration({ levels: ['error', 'warn'] })],
* });
* ```
*/
export const consoleLoggingIntegration = defineIntegration(_consoleLoggingIntegration);

function formatConsoleArgs(values: unknown[]): string {
return 'util' in GLOBAL_OBJ && typeof (GLOBAL_OBJ as GlobalObjectWithUtil).util.format === 'function'
? (GLOBAL_OBJ as GlobalObjectWithUtil).util.format(...values)
: safeJoin(values, ' ');
}
2 changes: 1 addition & 1 deletion packages/core/src/types-hoist/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export interface Log {
level: LogSeverityLevel;

/**
* The message to be logged - for example, 'hello world' would become a log like '[INFO] hello world'
* The message to be logged.
*/
message: ParameterizedString;

Expand Down
1 change: 1 addition & 0 deletions packages/google-cloud-serverless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export {
childProcessIntegration,
vercelAIIntegration,
logger,
consoleLoggingIntegration,
} from '@sentry/node';

export {
Expand Down
1 change: 1 addition & 0 deletions packages/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ export {
updateSpanName,
zodErrorsIntegration,
profiler,
consoleLoggingIntegration,
} from '@sentry/core';

export type {
Expand Down
1 change: 1 addition & 0 deletions packages/remix/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export {
withScope,
zodErrorsIntegration,
logger,
consoleLoggingIntegration,
} from '@sentry/node';

// Keeping the `*` exports for backwards compatibility and types
Expand Down
1 change: 1 addition & 0 deletions packages/solidstart/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ export {
withScope,
zodErrorsIntegration,
logger,
consoleLoggingIntegration,
} from '@sentry/node';

// We can still leave this for the carrier init and type exports
Expand Down
1 change: 1 addition & 0 deletions packages/sveltekit/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ export {
withScope,
zodErrorsIntegration,
logger,
consoleLoggingIntegration,
} from '@sentry/node';

// We can still leave this for the carrier init and type exports
Expand Down
Loading