Skip to content
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

feat(browser): Add logger.X methods to browser SDK #15763

Merged
merged 1 commit into from
Mar 21, 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
4 changes: 0 additions & 4 deletions packages/browser/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {
addAutoIpAddressToUser,
applySdkMetadata,
getSDKSource,
_INTERNAL_flushLogsBuffer,
} from '@sentry/core';
import { eventFromException, eventFromMessage } from './eventbuilder';
import { WINDOW } from './helpers';
Expand Down Expand Up @@ -86,9 +85,6 @@ export class BrowserClient extends Client<BrowserClientOptions> {
WINDOW.document.addEventListener('visibilitychange', () => {
if (WINDOW.document.visibilityState === 'hidden') {
this._flushOutcomes();
if (this._options._experiments?.enableLogs) {
_INTERNAL_flushLogsBuffer(this);
}
}
});
}
Expand Down
4 changes: 4 additions & 0 deletions packages/browser/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
export * from './exports';

import * as logger from './log';

export { logger };

export { reportingObserverIntegration } from './integrations/reportingobserver';
export { httpClientIntegration } from './integrations/httpclient';
export { contextLinesIntegration } from './integrations/contextlines';
Expand Down
186 changes: 186 additions & 0 deletions packages/browser/src/log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import type { LogSeverityLevel, Log, Client } 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);
});
}
Comment on lines +39 to +50
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we not also just flush in the client callback?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Which client callback are you referring too?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: string,
attributes?: Log['attributes'],
severityNumber?: Log['severityNumber'],
): void {
const client = getClient();
if (client) {
addFlushingListeners(client);

startFlushTimeout(client);
}

_INTERNAL_captureLog({ level, message, attributes, severityNumber }, client, undefined);
}

/**
* @summary Capture a log with the `trace` level. Requires `_experiments.enableLogs` to be enabled.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., userId: 100.
*
* @example
*
* ```
* Sentry.logger.trace('Hello world', { userId: 100 });
* ```
*/
export function trace(message: string, attributes?: Log['attributes']): void {
captureLog('trace', message, attributes);
}

/**
* @summary Capture a log with the `debug` level. Requires `_experiments.enableLogs` to be enabled.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., userId: 100.
*
* @example
*
* ```
* Sentry.logger.debug('Hello world', { userId: 100 });
* ```
*/
export function debug(message: string, attributes?: Log['attributes']): void {
captureLog('debug', message, attributes);
}

/**
* @summary Capture a log with the `info` level. Requires `_experiments.enableLogs` to be enabled.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., userId: 100.
*
* @example
*
* ```
* Sentry.logger.info('Hello world', { userId: 100 });
* ```
*/
export function info(message: string, attributes?: Log['attributes']): void {
captureLog('info', message, attributes);
}

/**
* @summary Capture a log with the `warn` level. Requires `_experiments.enableLogs` to be enabled.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., userId: 100.
*
* @example
*
* ```
* Sentry.logger.warn('Hello world', { userId: 100 });
* ```
*/
export function warn(message: string, attributes?: Log['attributes']): void {
captureLog('warn', message, attributes);
}

/**
* @summary Capture a log with the `error` level. Requires `_experiments.enableLogs` to be enabled.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., userId: 100.
*
* @example
*
* ```
* Sentry.logger.error('Hello world', { userId: 100 });
* ```
*/
export function error(message: string, attributes?: Log['attributes']): void {
captureLog('error', message, attributes);
}

/**
* @summary Capture a log with the `fatal` level. Requires `_experiments.enableLogs` to be enabled.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., userId: 100.
*
* @example
*
* ```
* Sentry.logger.fatal('Hello world', { userId: 100 });
* ```
*/
export function fatal(message: string, attributes?: Log['attributes']): void {
captureLog('fatal', message, attributes);
}

/**
* @summary Capture a log with the `critical` level. Requires `_experiments.enableLogs` to be enabled.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., userId: 100.
*
* @example
*
* ```
* Sentry.logger.critical('Hello world', { userId: 100 });
* ```
*/
export function critical(message: string, attributes?: Log['attributes']): void {
captureLog('critical', message, attributes);
}
43 changes: 29 additions & 14 deletions packages/browser/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
getCurrentScope,
init,
showReportDialog,
logger,
} from '../src';
import { getDefaultBrowserClientOptions } from './helper/browser-client-options';
import { makeSimpleTransport } from './mocks/simpletransport';
Expand Down Expand Up @@ -243,20 +244,21 @@ describe('SentryBrowser', () => {
expect(event.exception.values[0]?.stacktrace.frames).not.toHaveLength(0);
});

it('should capture a message', done => {
const options = getDefaultBrowserClientOptions({
beforeSend: (event: Event): Event | null => {
expect(event.level).toBe('info');
expect(event.message).toBe('test');
expect(event.exception).toBeUndefined();
done();
return event;
},
dsn,
});
setCurrentClient(new BrowserClient(options));
captureMessage('test');
});
it('should capture an message', () =>
new Promise<void>(resolve => {
const options = getDefaultBrowserClientOptions({
beforeSend: event => {
expect(event.level).toBe('info');
expect(event.message).toBe('test');
expect(event.exception).toBeUndefined();
resolve();
return event;
},
dsn,
});
setCurrentClient(new BrowserClient(options));
captureMessage('test');
}));

it('should capture an event', () =>
new Promise<void>(resolve => {
Expand Down Expand Up @@ -322,6 +324,19 @@ describe('SentryBrowser', () => {
expect(localBeforeSend).not.toHaveBeenCalled();
});
});

describe('logger', () => {
it('exports all log methods', () => {
expect(logger).toBeDefined();
expect(logger.trace).toBeDefined();
expect(logger.debug).toBeDefined();
expect(logger.info).toBeDefined();
expect(logger.warn).toBeDefined();
expect(logger.error).toBeDefined();
expect(logger.fatal).toBeDefined();
expect(logger.critical).toBeDefined();
});
});
});

describe('SentryBrowser initialization', () => {
Expand Down
Loading
Loading