Skip to content
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
7 changes: 5 additions & 2 deletions src/common/ipc.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { SerializedLog } from '@sentry/core';

/** Ways to communicate between the renderer and main process */
export enum IPCMode {
/** Configures Electron IPC to receive messages from renderers */
Expand All @@ -24,8 +26,8 @@ export enum IPCChannel {
ENVELOPE = 'sentry-electron.envelope',
/** IPC to pass renderer status updates */
STATUS = 'sentry-electron.status',
/** IPC to pass renderer metric additions to the main process */
ADD_METRIC = 'sentry-electron.add-metric',
/** IPC to pass structured log messages */
STRUCTURED_LOG = 'sentry-electron.structured-log',
}

export interface RendererProcessAnrOptions {
Expand Down Expand Up @@ -59,6 +61,7 @@ export interface IPCInterface {
sendScope: (scope: string) => void;
sendEnvelope: (evn: Uint8Array | string) => void;
sendStatus: (state: RendererStatus) => void;
sendStructuredLog: (log: SerializedLog) => void;
}

export const RENDERER_ID_HEADER = 'sentry-electron-renderer-id';
Expand Down
33 changes: 32 additions & 1 deletion src/main/ipc.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
import { Attachment, Client, DynamicSamplingContext, Event, logger, parseEnvelope, ScopeData } from '@sentry/core';
import {
_INTERNAL_captureSerializedLog,
Attachment,
Client,
DynamicSamplingContext,
Event,
logger,
parseEnvelope,
ScopeData,
SerializedLog,
} from '@sentry/core';
import { captureEvent, getClient, getCurrentScope } from '@sentry/node';
import { app, ipcMain, protocol, WebContents, webContents } from 'electron';
import { eventFromEnvelope } from '../common/envelope';
Expand All @@ -9,6 +19,7 @@ import { rendererProfileFromIpc } from './integrations/renderer-profiling';
import { mergeEvents } from './merge';
import { normalizeReplayEnvelope } from './normalize';
import { ElectronMainOptionsInternal } from './sdk';
import { SDK_VERSION } from './version';

let KNOWN_RENDERERS: Set<number> | undefined;
let WINDOW_ID_TO_WEB_CONTENTS: Map<string, number> | undefined;
Expand Down Expand Up @@ -154,6 +165,23 @@ function handleScope(options: ElectronMainOptionsInternal, jsonScope: string): v
}
}

function handleLogFromRenderer(client: Client, options: ElectronMainOptionsInternal, log: SerializedLog): void {
log.attributes = log.attributes || {};

if (options.release) {
log.attributes['sentry.release'] = { value: options.release, type: 'string' };
}

if (options.environment) {
log.attributes['sentry.environment'] = { value: options.environment, type: 'string' };
}

log.attributes['sentry.sdk.name'] = { value: 'sentry.javascript.electron', type: 'string' };
log.attributes['sentry.sdk.version'] = { value: SDK_VERSION, type: 'string' };

_INTERNAL_captureSerializedLog(client, log);
}

/** Enables Electron protocol handling */
function configureProtocol(client: Client, options: ElectronMainOptionsInternal): void {
if (app.isReady()) {
Expand Down Expand Up @@ -189,6 +217,8 @@ function configureProtocol(client: Client, options: ElectronMainOptionsInternal)
handleScope(options, data.toString());
} else if (request.url.startsWith(`${PROTOCOL_SCHEME}://${IPCChannel.ENVELOPE}`) && data) {
handleEnvelope(client, options, data, getWebContents());
} else if (request.url.startsWith(`${PROTOCOL_SCHEME}://${IPCChannel.STRUCTURED_LOG}`) && data) {
handleLogFromRenderer(client, options, JSON.parse(data.toString()));
} else if (
rendererStatusChanged &&
request.url.startsWith(`${PROTOCOL_SCHEME}://${IPCChannel.STATUS}`) &&
Expand Down Expand Up @@ -232,6 +262,7 @@ function configureClassic(client: Client, options: ElectronMainOptionsInternal):
ipcMain.on(IPCChannel.ENVELOPE, ({ sender }, env: Uint8Array | string) =>
handleEnvelope(client, options, env, sender),
);
ipcMain.on(IPCChannel.STRUCTURED_LOG, (_, log: SerializedLog) => handleLogFromRenderer(client, options, log));

const rendererStatusChanged = createRendererAnrStatusHandler(client);
if (rendererStatusChanged) {
Expand Down
9 changes: 9 additions & 0 deletions src/main/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,15 @@ export function init(userOptions: ElectronMainOptions): void {

const client = new NodeClient(options);

if (options._experiments?.enableLogs) {
// In Electron we don't want to capture the hostname in log attributes
client.on('beforeCaptureLog', (log) => {
if (log.attributes?.['server.address']) {
delete log.attributes['server.address'];
}
});
}

if (options.sendDefaultPii === true) {
client.on('postprocessEvent', addAutoIpAddressToUser);
client.on('beforeSendSession', addAutoIpAddressToSession);
Expand Down
2 changes: 2 additions & 0 deletions src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* This preload script may be used with sandbox mode enabled which means regular require is not available.
*/

import { SerializedLog } from '@sentry/core';
import { contextBridge, ipcRenderer } from 'electron';
import { IPCChannel, RendererStatus } from '../common/ipc';

Expand All @@ -15,6 +16,7 @@ if (window.__SENTRY_IPC__) {
sendScope: (scopeJson: string) => ipcRenderer.send(IPCChannel.SCOPE, scopeJson),
sendEnvelope: (envelope: Uint8Array | string) => ipcRenderer.send(IPCChannel.ENVELOPE, envelope),
sendStatus: (status: RendererStatus) => ipcRenderer.send(IPCChannel.STATUS, status),
sendStructuredLog: (log: SerializedLog) => ipcRenderer.send(IPCChannel.STRUCTURED_LOG, log),
};

// eslint-disable-next-line no-restricted-globals
Expand Down
5 changes: 4 additions & 1 deletion src/renderer/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import * as logger from './log';

export { logger };

export type {
Breadcrumb,
BreadcrumbHint,
Expand Down Expand Up @@ -68,7 +72,6 @@ export {
isEnabled,
isInitialized,
lastEventId,
logger,
linkedErrorsIntegration,
moduleMetadataIntegration,
onLoad,
Expand Down
11 changes: 10 additions & 1 deletion src/renderer/ipc.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable no-restricted-globals */
/* eslint-disable no-console */
import { logger, uuid4 } from '@sentry/core';
import { logger, SerializedLog, uuid4 } from '@sentry/core';
import { IPCChannel, IPCInterface, PROTOCOL_SCHEME, RENDERER_ID_HEADER, RendererStatus } from '../common/ipc';

function buildUrl(channel: IPCChannel): string {
Expand Down Expand Up @@ -46,6 +46,15 @@ function getImplementation(): IPCInterface {
// ignore
});
},
sendStructuredLog: (log: SerializedLog) => {
fetch(buildUrl(IPCChannel.STRUCTURED_LOG), {
method: 'POST',
body: JSON.stringify(log),
headers,
}).catch(() => {
// ignore
});
},
};
}
}
Expand Down
210 changes: 210 additions & 0 deletions src/renderer/log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
import {
_INTERNAL_captureLog,
getClient,
getCurrentScope,
Log,
LogSeverityLevel,
ParameterizedString,
SerializedLog,
} from '@sentry/core';
import { getIPC } from './ipc';

function captureLog(
level: LogSeverityLevel,
message: ParameterizedString,
attributes?: Log['attributes'],
severityNumber?: Log['severityNumber'],
): void {
_INTERNAL_captureLog(
{ level, message, attributes, severityNumber },
getClient(),
getCurrentScope(),
(_: unknown, log: SerializedLog) => getIPC().sendStructuredLog(log),
);
}

/**
* @summary Capture a log with the `trace` level. Requires `_experiments.enableLogs` to be enabled in the Electron main process.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., { userId: 100, route: '/dashboard' }.
*
* @example
*
* ```
* Sentry.logger.trace('User clicked submit button', {
* buttonId: 'submit-form',
* formId: 'user-profile',
* timestamp: Date.now()
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.trace(Sentry.logger.fmt`User ${user} navigated to ${page}`, {
* userId: '123',
* sessionId: 'abc-xyz'
* });
* ```
*/
export function trace(message: ParameterizedString, attributes?: Log['attributes']): void {
captureLog('trace', message, attributes);
}

/**
* @summary Capture a log with the `debug` level. Requires `_experiments.enableLogs` to be enabled in the Electron main process.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., { component: 'Header', state: 'loading' }.
*
* @example
*
* ```
* Sentry.logger.debug('Component mounted', {
* component: 'UserProfile',
* props: { userId: 123 },
* renderTime: 150
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.debug(Sentry.logger.fmt`API request to ${endpoint} failed`, {
* statusCode: 404,
* requestId: 'req-123',
* duration: 250
* });
* ```
*/
export function debug(message: ParameterizedString, attributes?: Log['attributes']): void {
captureLog('debug', message, attributes);
}

/**
* @summary Capture a log with the `info` level. Requires `_experiments.enableLogs` to be enabled in the Electron main process.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., { feature: 'checkout', status: 'completed' }.
*
* @example
*
* ```
* Sentry.logger.info('User completed checkout', {
* orderId: 'order-123',
* amount: 99.99,
* paymentMethod: 'credit_card'
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.info(Sentry.logger.fmt`User ${user} updated profile picture`, {
* userId: 'user-123',
* imageSize: '2.5MB',
* timestamp: Date.now()
* });
* ```
*/
export function info(message: ParameterizedString, attributes?: Log['attributes']): void {
captureLog('info', message, attributes);
}

/**
* @summary Capture a log with the `warn` level. Requires `_experiments.enableLogs` to be enabled in the Electron main process.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., { browser: 'Chrome', version: '91.0' }.
*
* @example
*
* ```
* Sentry.logger.warn('Browser compatibility issue detected', {
* browser: 'Safari',
* version: '14.0',
* feature: 'WebRTC',
* fallback: 'enabled'
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.warn(Sentry.logger.fmt`API endpoint ${endpoint} is deprecated`, {
* recommendedEndpoint: '/api/v2/users',
* sunsetDate: '2024-12-31',
* clientVersion: '1.2.3'
* });
* ```
*/
export function warn(message: ParameterizedString, attributes?: Log['attributes']): void {
captureLog('warn', message, attributes);
}

/**
* @summary Capture a log with the `error` level. Requires `_experiments.enableLogs` to be enabled in the Electron main process.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., { error: 'NetworkError', url: '/api/data' }.
*
* @example
*
* ```
* Sentry.logger.error('Failed to load user data', {
* error: 'NetworkError',
* url: '/api/users/123',
* statusCode: 500,
* retryCount: 3
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.error(Sentry.logger.fmt`Payment processing failed for order ${orderId}`, {
* error: 'InsufficientFunds',
* amount: 100.00,
* currency: 'USD',
* userId: 'user-456'
* });
* ```
*/
export function error(message: ParameterizedString, attributes?: Log['attributes']): void {
captureLog('error', message, attributes);
}

/**
* @summary Capture a log with the `fatal` level. Requires `_experiments.enableLogs` to be enabled in the Electron main process.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., { appState: 'corrupted', sessionId: 'abc-123' }.
*
* @example
*
* ```
* Sentry.logger.fatal('Application state corrupted', {
* lastKnownState: 'authenticated',
* sessionId: 'session-123',
* timestamp: Date.now(),
* recoveryAttempted: true
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.fatal(Sentry.logger.fmt`Critical system failure in ${service}`, {
* service: 'payment-processor',
* errorCode: 'CRITICAL_FAILURE',
* affectedUsers: 150,
* timestamp: Date.now()
* });
* ```
*/
export function fatal(message: ParameterizedString, attributes?: Log['attributes']): void {
captureLog('fatal', message, attributes);
}

export { fmt } from '@sentry/core';
9 changes: 9 additions & 0 deletions test/e2e/test-apps/other/renderer-error/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "javascript-logs",
"description": "JavaScript Structural Logging",
"version": "1.0.0",
"main": "src/main.js",
"dependencies": {
"@sentry/electron": "5.6.0"
}
}
Loading