Skip to content

ref(browser/core): Move all log flushing logic into clients #15831

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
Mar 28, 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
34 changes: 31 additions & 3 deletions packages/browser/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,14 @@ import {
addAutoIpAddressToUser,
applySdkMetadata,
getSDKSource,
_INTERNAL_flushLogsBuffer,
} from '@sentry/core';
import { eventFromException, eventFromMessage } from './eventbuilder';
import { WINDOW } from './helpers';
import type { BrowserTransportOptions } from './transports/types';

const DEFAULT_FLUSH_INTERVAL = 5000;

/**
* Configuration options for the Sentry Browser SDK.
* @see @sentry/core Options for more information.
Expand Down Expand Up @@ -65,6 +68,7 @@ export type BrowserClientOptions = ClientOptions<BrowserTransportOptions> &
* @see SentryClient for usage documentation.
*/
export class BrowserClient extends Client<BrowserClientOptions> {
private _logFlushIdleTimeout: ReturnType<typeof setTimeout> | undefined;
/**
* Creates a new Browser SDK instance.
*
Expand All @@ -81,17 +85,41 @@ export class BrowserClient extends Client<BrowserClientOptions> {

super(opts);

// eslint-disable-next-line @typescript-eslint/no-this-alias
const client = this;
const { sendDefaultPii, _experiments } = client._options;
const enableLogs = _experiments?.enableLogs;

if (opts.sendClientReports && WINDOW.document) {
WINDOW.document.addEventListener('visibilitychange', () => {
if (WINDOW.document.visibilityState === 'hidden') {
this._flushOutcomes();
if (enableLogs) {
_INTERNAL_flushLogsBuffer(client);
}
}
});
}

if (this._options.sendDefaultPii) {
this.on('postprocessEvent', addAutoIpAddressToUser);
this.on('beforeSendSession', addAutoIpAddressToSession);
if (enableLogs) {
client.on('flush', () => {
_INTERNAL_flushLogsBuffer(client);
});

client.on('afterCaptureLog', () => {
if (client._logFlushIdleTimeout) {
clearTimeout(client._logFlushIdleTimeout);
}

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

if (sendDefaultPii) {
client.on('postprocessEvent', addAutoIpAddressToUser);
client.on('beforeSendSession', addAutoIpAddressToSession);
}
}

Expand Down
61 changes: 3 additions & 58 deletions packages/browser/src/log.ts
Original file line number Diff line number Diff line change
@@ -1,53 +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);
});
}
import type { LogSeverityLevel, Log, ParameterizedString } from '@sentry/core';
import { _INTERNAL_captureLog } from '@sentry/core';

/**
* Capture a log with the given level.
Expand All @@ -63,14 +15,7 @@ function captureLog(
attributes?: Log['attributes'],
severityNumber?: Log['severityNumber'],
): void {
const client = getClient();
if (client) {
addFlushingListeners(client);

startFlushTimeout(client);
}

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

/**
Expand Down
120 changes: 120 additions & 0 deletions packages/browser/test/client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/**
* @vitest-environment jsdom
*/

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as sentryCore from '@sentry/core';
import { BrowserClient } from '../src/client';
import { WINDOW } from '../src/helpers';
import { getDefaultBrowserClientOptions } from './helper/browser-client-options';

vi.mock('@sentry/core', async requireActual => {
return {
...((await requireActual()) as any),
_INTERNAL_flushLogsBuffer: vi.fn(),
};
});

describe('BrowserClient', () => {
let client: BrowserClient;
const DEFAULT_FLUSH_INTERVAL = 5000;

afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
});

it('does not flush logs when logs are disabled', () => {
client = new BrowserClient(
getDefaultBrowserClientOptions({
_experiments: { enableLogs: false },
sendClientReports: true,
}),
);

// Add some logs
sentryCore._INTERNAL_captureLog({ level: 'info', message: 'test log 1' }, client);
sentryCore._INTERNAL_captureLog({ level: 'info', message: 'test log 2' }, client);

// Simulate visibility change to hidden
if (WINDOW.document) {
Object.defineProperty(WINDOW.document, 'visibilityState', { value: 'hidden' });
WINDOW.document.dispatchEvent(new Event('visibilitychange'));
}

expect(sentryCore._INTERNAL_flushLogsBuffer).not.toHaveBeenCalled();
});

describe('log flushing', () => {
beforeEach(() => {
vi.useFakeTimers();
client = new BrowserClient(
getDefaultBrowserClientOptions({
_experiments: { enableLogs: true },
sendClientReports: true,
}),
);
});

it('flushes logs when page visibility changes to hidden', () => {
const flushOutcomesSpy = vi.spyOn(client as any, '_flushOutcomes');

// Add some logs
sentryCore._INTERNAL_captureLog({ level: 'info', message: 'test log 1' }, client);
sentryCore._INTERNAL_captureLog({ level: 'info', message: 'test log 2' }, client);

// Simulate visibility change to hidden
if (WINDOW.document) {
Object.defineProperty(WINDOW.document, 'visibilityState', { value: 'hidden' });
WINDOW.document.dispatchEvent(new Event('visibilitychange'));
}

expect(flushOutcomesSpy).toHaveBeenCalled();
expect(sentryCore._INTERNAL_flushLogsBuffer).toHaveBeenCalledWith(client);
});

it('flushes logs on flush event', () => {
// Add some logs
sentryCore._INTERNAL_captureLog({ level: 'info', message: 'test log 1' }, client);
sentryCore._INTERNAL_captureLog({ level: 'info', message: 'test log 2' }, client);

// Trigger flush event
client.emit('flush');

expect(sentryCore._INTERNAL_flushLogsBuffer).toHaveBeenCalledWith(client);
});

it('flushes logs after idle timeout', () => {
// Add a log which will trigger afterCaptureLog event
sentryCore._INTERNAL_captureLog({ level: 'info', message: 'test log' }, client);

// Fast forward the idle timeout
vi.advanceTimersByTime(DEFAULT_FLUSH_INTERVAL);

expect(sentryCore._INTERNAL_flushLogsBuffer).toHaveBeenCalledWith(client);
});

it('resets idle timeout when new logs are captured', () => {
// Add initial log
sentryCore._INTERNAL_captureLog({ level: 'info', message: 'test log 1' }, client);

// Fast forward part of the idle timeout
vi.advanceTimersByTime(DEFAULT_FLUSH_INTERVAL / 2);

// Add another log which should reset the timeout
sentryCore._INTERNAL_captureLog({ level: 'info', message: 'test log 2' }, client);

// Fast forward the remaining time
vi.advanceTimersByTime(DEFAULT_FLUSH_INTERVAL / 2);

// Should not have flushed yet since timeout was reset
expect(sentryCore._INTERNAL_flushLogsBuffer).not.toHaveBeenCalled();

// Fast forward the full timeout
vi.advanceTimersByTime(DEFAULT_FLUSH_INTERVAL);

// Now should have flushed both logs
expect(sentryCore._INTERNAL_flushLogsBuffer).toHaveBeenCalledWith(client);
});
});
});
Loading
Loading