Skip to content

feat(browser): Add console logging integration #15828

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

Closed
wants to merge 1 commit into from
Closed
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
4 changes: 2 additions & 2 deletions packages/browser/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
export * from './exports';

import * as logger from './log';

import * as logger from './logs/exports';
export { logger };
export { consoleLoggingIntegration } from './logs/console-integration';

export { reportingObserverIntegration } from './integrations/reportingobserver';
export { httpClientIntegration } from './integrations/httpclient';
Expand Down
73 changes: 73 additions & 0 deletions packages/browser/src/logs/capture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import type { Client, Log, LogSeverityLevel, ParameterizedString } from '@sentry/core';
import { getClient, _INTERNAL_captureLog, _INTERNAL_flushLogsBuffer } from '@sentry/core';
import { WINDOW } from '../helpers';

/**
* TODO: Make this configurable
*/
const DEFAULT_FLUSH_INTERVAL = 5000;

let timeout: ReturnType<typeof setTimeout> | undefined;

/**
* This is a global timeout that is used to flush the logs buffer.
* It is used to ensure that logs are flushed even if the client is not flushed.
*/
function startFlushTimeout(client: Client): void {
if (timeout) {
clearTimeout(timeout);
}

timeout = setTimeout(() => {
_INTERNAL_flushLogsBuffer(client);
}, DEFAULT_FLUSH_INTERVAL);
}

let isClientListenerAdded = false;
/**
* This is a function that is used to add a flush listener to the client.
* It is used to ensure that the logger buffer is flushed when the client is flushed.
*/
function addFlushingListeners(client: Client): void {
if (isClientListenerAdded || !client.getOptions()._experiments?.enableLogs) {
return;
}

isClientListenerAdded = true;

if (WINDOW.document) {
WINDOW.document.addEventListener('visibilitychange', () => {
if (WINDOW.document.visibilityState === 'hidden') {
_INTERNAL_flushLogsBuffer(client);
}
});
}

client.on('flush', () => {
_INTERNAL_flushLogsBuffer(client);
});
}

/**
* Capture a log with the given level.
*
* @param level - The level of the log.
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., userId: 100.
* @param severityNumber - The severity number of the log.
*/
export function captureLog(
level: LogSeverityLevel,
message: ParameterizedString,
attributes?: Log['attributes'],
severityNumber?: Log['severityNumber'],
): void {
const client = getClient();
if (client) {
addFlushingListeners(client);

startFlushTimeout(client);
}

_INTERNAL_captureLog({ level, message, attributes, severityNumber }, client, undefined);
}
69 changes: 69 additions & 0 deletions packages/browser/src/logs/console-integration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import type { ConsoleLevel, IntegrationFn } from '@sentry/core';
import {
addConsoleInstrumentationHandler,
logger,
CONSOLE_LEVELS,
defineIntegration,
safeJoin,
getClient,
} from '@sentry/core';
import { captureLog } from './capture';
import { DEBUG_BUILD } from '../debug-build';

interface CaptureConsoleOptions {
levels: ConsoleLevel[];
}

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 message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;
captureLog('error', message);
}
return;
}

const message = safeJoin(args, ' ');
captureLog(level === 'log' ? 'info' : level, message);
});
},
};
}) 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);
Original file line number Diff line number Diff line change
@@ -1,77 +1,5 @@
import type { LogSeverityLevel, Log, Client, ParameterizedString } from '@sentry/core';
import { getClient, _INTERNAL_captureLog, _INTERNAL_flushLogsBuffer } from '@sentry/core';

import { WINDOW } from './helpers';

/**
* TODO: Make this configurable
*/
const DEFAULT_FLUSH_INTERVAL = 5000;

let timeout: ReturnType<typeof setTimeout> | undefined;

/**
* This is a global timeout that is used to flush the logs buffer.
* It is used to ensure that logs are flushed even if the client is not flushed.
*/
function startFlushTimeout(client: Client): void {
if (timeout) {
clearTimeout(timeout);
}

timeout = setTimeout(() => {
_INTERNAL_flushLogsBuffer(client);
}, DEFAULT_FLUSH_INTERVAL);
}

let isClientListenerAdded = false;
/**
* This is a function that is used to add a flush listener to the client.
* It is used to ensure that the logger buffer is flushed when the client is flushed.
*/
function addFlushingListeners(client: Client): void {
if (isClientListenerAdded || !client.getOptions()._experiments?.enableLogs) {
return;
}

isClientListenerAdded = true;

if (WINDOW.document) {
WINDOW.document.addEventListener('visibilitychange', () => {
if (WINDOW.document.visibilityState === 'hidden') {
_INTERNAL_flushLogsBuffer(client);
}
});
}

client.on('flush', () => {
_INTERNAL_flushLogsBuffer(client);
});
}

/**
* Capture a log with the given level.
*
* @param level - The level of the log.
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., userId: 100.
* @param severityNumber - The severity number of the log.
*/
function captureLog(
level: LogSeverityLevel,
message: ParameterizedString,
attributes?: Log['attributes'],
severityNumber?: Log['severityNumber'],
): void {
const client = getClient();
if (client) {
addFlushingListeners(client);

startFlushTimeout(client);
}

_INTERNAL_captureLog({ level, message, attributes, severityNumber }, client, undefined);
}
import type { Log, ParameterizedString } from '@sentry/core';
import { captureLog } from './capture';

/**
* @summary Capture a log with the `trace` level. Requires `_experiments.enableLogs` to be enabled.
Expand Down
Loading
Loading