Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
add processing functions
  • Loading branch information
s1gr1d committed Feb 27, 2026
commit 73e9c4a3cc904083ab4bde6ea674242919c57025
132 changes: 120 additions & 12 deletions packages/core/src/integrations/consola.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,36 @@
import type { Client } from '../client';
import { getClient } from '../currentScopes';
import { _INTERNAL_captureLog } from '../logs/internal';
import { formatConsoleArgs } from '../logs/utils';
import { createConsoleTemplateAttributes, formatConsoleArgs, hasConsoleSubstitutions } from '../logs/utils';
import type { LogSeverityLevel } from '../types-hoist/log';
import { isPlainObject } from '../utils/is';
import { normalize } from '../utils/normalize';

/**
* Result of extracting structured attributes from console arguments.
*/
export interface ExtractAttributesResult {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

l: I would not export this as long as the functions stays internal.

/**
* The log message to use for the log entry, typically constructed from the console arguments.
*/
message?: string;

/**
* The parameterized template string which is added as `sentry.message.template` attribute if applicable.
*/
messageTemplate?: string;

/**
* Remaining arguments to process as attributes with keys like `sentry.message.parameter.0`, `sentry.message.parameter.1`, etc.
*/
messageParameters?: unknown[];

/**
* Additional attributes to add to the log.
*/
attributes?: Record<string, unknown>;
}

/**
* Options for the Sentry Consola reporter.
*/
Expand Down Expand Up @@ -220,16 +246,6 @@ export function createConsolaReporter(options: ConsolaReporterOptions = {}): Con

const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = client.getOptions();

// Format the log message using the same approach as consola's basic reporter
const messageParts = [];
if (consolaMessage) {
messageParts.push(consolaMessage);
}
if (args && args.length > 0) {
messageParts.push(formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth));
}
const message = messageParts.join(' ');

const attributes: Record<string, unknown> = {};

// Build attributes
Expand All @@ -252,9 +268,23 @@ export function createConsolaReporter(options: ConsolaReporterOptions = {}): Con
attributes['consola.level'] = level;
}

const extractionResult = processExtractedAttributes(
defaultExtractAttributes(args, normalizeDepth, normalizeMaxBreadth),
normalizeDepth,
normalizeMaxBreadth,
);

if (extractionResult?.attributes) {
Object.assign(attributes, extractionResult.attributes);
}

_INTERNAL_captureLog({
level: logSeverityLevel,
message,
message:
extractionResult?.message ||
consolaMessage ||
(args && formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth)) ||
'',
attributes,
});
},
Expand Down Expand Up @@ -330,3 +360,81 @@ function getLogSeverityLevel(type?: string, level?: number | null): LogSeverityL
// Default fallback
return 'info';
}

/**
* Extracts structured attributes from console arguments. If the first argument is a plain object, its properties are extracted as attributes.
*/
function defaultExtractAttributes(
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is a function that could be theoretically added by users (as a future feature). That's why this function is extra from the processExtractedAttributes. In theory, it could just be one function.

args: unknown[] | undefined,
normalizeDepth: number,
normalizeMaxBreadth: number,
): ExtractAttributesResult {
if (!args?.length) {
return { message: '' };
}

// Message looks like how consola logs the message to the console (all args stringified and joined)
const message = formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth);

const firstArg = args[0];

if (isPlainObject(firstArg)) {
// Remaining args start from index 2 i f we used second arg as message, otherwise from index 1
const remainingArgsStartIndex = typeof args[1] === 'string' ? 2 : 1;
const remainingArgs = args.slice(remainingArgsStartIndex);

return {
message,
// Object content from first arg is added as attributes
attributes: firstArg,
// Add remaining args as message parameters
messageParameters: remainingArgs,
};
} else {
const followingArgs = args.slice(1);

const hasStringSubstitutions =
followingArgs.length > 0 && typeof firstArg === 'string' && !hasConsoleSubstitutions(firstArg);
Comment thread
s1gr1d marked this conversation as resolved.

return {
message,
messageTemplate: hasStringSubstitutions ? firstArg : undefined,
messageParameters: hasStringSubstitutions ? followingArgs : undefined,
};
}
}

/**
* Processes extracted attributes by normalizing them and preparing message parameter attributes if a template is present.
*/
function processExtractedAttributes(
extractionResult: ExtractAttributesResult,
normalizeDepth: number,
normalizeMaxBreadth: number,
): { message: string | undefined; attributes: Record<string, unknown> } {
const { message, attributes, messageTemplate, messageParameters } = extractionResult;

const messageParamAttributes: Record<string, unknown> = {};

if (messageTemplate && messageParameters) {
const templateAttrs = createConsoleTemplateAttributes(messageTemplate, messageParameters);

for (const [key, value] of Object.entries(templateAttrs)) {
messageParamAttributes[key] = key.startsWith('sentry.message.parameter.')
? normalize(value, normalizeDepth, normalizeMaxBreadth)
: value;
}
} else if (messageParameters && messageParameters.length > 0) {
messageParameters.forEach((arg, index) => {
messageParamAttributes[`sentry.message.parameter.${index}`] = normalize(arg, normalizeDepth, normalizeMaxBreadth);
});
}

return {
message: message,
attributes: {
...normalize(attributes, normalizeDepth, normalizeMaxBreadth),
Comment thread
cursor[bot] marked this conversation as resolved.
...messageParamAttributes,
},
};
}
184 changes: 153 additions & 31 deletions packages/core/test/lib/integrations/consola.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,10 @@ describe('createConsolaReporter', () => {
});

it('should format message from args', () => {
const logObj = {
sentryReporter.log({
type: 'info',
args: ['Hello', 'world', 123, { key: 'value' }],
};

sentryReporter.log(logObj);
});

expect(formatConsoleArgs).toHaveBeenCalledWith(['Hello', 'world', 123, { key: 'value' }], 3, 1000);
expect(_INTERNAL_captureLog).toHaveBeenCalledWith({
Expand All @@ -147,60 +145,184 @@ describe('createConsolaReporter', () => {
attributes: {
'sentry.origin': 'auto.log.consola',
'consola.type': 'info',
'sentry.message.parameter.0': 'world',
'sentry.message.parameter.1': 123,
'sentry.message.parameter.2': { key: 'value' },
'sentry.message.template': 'Hello {} {} {}',
},
});
});

it('uses consolaMessage when result.message is empty (e.g. args is [])', () => {
sentryReporter.log({
type: 'info',
message: 'From consola message key',
args: [],
});

const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0];
expect(call.message).toBe('From consola message key');
});

it('uses formatConsoleArgs when result.message and consolaMessage are falsy but args is truthy', () => {
sentryReporter.log({
type: 'info',
args: [],
});

expect(formatConsoleArgs).toHaveBeenCalledWith([], 3, 1000);
const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0];
expect(call.message).toBe('');
});

it('overrides consola.tag or sentry.origin with object properties', () => {
sentryReporter.log({
type: 'info',
message: 'Test',
tag: 'api',
args: [{ 'sentry.origin': 'object-args', 'consola.tag': 'object-args-tag' }, 'Test'],
});

const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0];
expect(call.attributes?.['sentry.origin']).toBe('object-args');
expect(call.attributes?.['consola.tag']).toBe('object-args-tag');
});

it('respects normalizeDepth in fallback mode', () => {
sentryReporter.log({
type: 'info',
args: [
'Deep',
{
level1: { level2: { level3: { level4: 'deep' } } },
simpleKey: 'simple value',
},
],
});

const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0];
expect(call.attributes?.['sentry.message.parameter.0']).toEqual({
level1: { level2: { level3: '[Object]' } },
simpleKey: 'simple value',
});
});

it('adds additional params in object-first mode', () => {
sentryReporter.log({
type: 'info',
args: [
{
level1: { level2: { level3: { level4: 'deep' } } },
simpleKey: 'simple value',
},
'Deep object',
12345,
{ another: 'object', level1: { level2: { level3: { level4: 'deep' } } } },
],
});

const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0];
expect(call.message).toBe(
'{"level1":{"level2":{"level3":"[Object]"}},"simpleKey":"simple value"} Deep object 12345 {"another":"object","level1":{"level2":{"level3":"[Object]"}}}',
);
expect(call.attributes?.level1).toEqual({ level2: { level3: '[Object]' } });
expect(call.attributes?.simpleKey).toBe('simple value');

expect(call.attributes?.['sentry.message.template']).toBeUndefined();
expect(call.attributes?.['sentry.message.parameter.0']).toBe(12345);
expect(call.attributes?.['sentry.message.parameter.1']).toStrictEqual({
another: 'object',
level1: { level2: { level3: '[Object]' } },
});
});

it('stores Date and Error in message params (fallback)', () => {
const date = new Date('2023-01-01T00:00:00.000Z');
sentryReporter.log({ type: 'info', args: ['Time:', date] });
expect(vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]!.attributes?.['sentry.message.parameter.0']).toBe(
'2023-01-01T00:00:00.000Z',
);

vi.clearAllMocks();
const err = new Error('Test error');
sentryReporter.log({ type: 'error', args: ['Error occurred:', err] });
const errCall = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0];
expect(errCall.attributes?.['sentry.message.parameter.0']).toMatchObject({
message: 'Test error',
name: 'Error',
});
});

it('handles console substitution patterns in first arg', () => {
sentryReporter.log({ type: 'info', args: ['Value: %d, another: %s', 42, 'hello'] });
const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0];

// We don't substitute as it gets too complicated on the client-side: https://github.com/getsentry/sentry-javascript/pull/17703
expect(call.message).toBe('Value: %d, another: %s 42 hello');
expect(call.attributes?.['sentry.message.template']).toBeUndefined();
expect(call.attributes?.['sentry.message.parameter.0']).toBeUndefined();
});

it.each([
['string', ['Normal log', { data: 1 }, 123], 'Normal log {} {}', undefined],
['array', [[1, 2, 3], 'Array data'], undefined, undefined],
['Error', [new Error('Test'), 'Error occurred'], undefined, 'error'],
] as const)('falls back to non-object extracting when first arg is %s', (_, args, template, level) => {
vi.clearAllMocks();
// @ts-expect-error Testing legacy fallback
sentryReporter.log({ type: level ?? 'info', args });
expect(formatConsoleArgs).toHaveBeenCalled();
const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0];
if (template !== undefined) expect(call.attributes?.['sentry.message.template']).toBe(template);
if (template === 'Normal log {} {}') expect(call.attributes?.data).toBeUndefined();
if (level) expect(call.level).toBe(level);
});

it('object-first: empty object as first arg', () => {
sentryReporter.log({ type: 'info', args: [{}, 'Empty object log'] });
const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0];
expect(call.message).toBe('{} Empty object log');
expect(call.attributes?.['sentry.origin']).toBe('auto.log.consola');
});

it('should handle args with unparseable objects', () => {
const circular: any = {};
circular.self = circular;

const logObj = {
sentryReporter.log({
type: 'info',
args: ['Message', circular],
};

sentryReporter.log(logObj);
});

expect(_INTERNAL_captureLog).toHaveBeenCalledWith({
level: 'info',
message: 'Message {"self":"[Circular ~]"}',
attributes: {
'sentry.origin': 'auto.log.consola',
'consola.type': 'info',
'sentry.message.template': 'Message {}',
'sentry.message.parameter.0': { self: '[Circular ~]' },
},
});
});

it('consola-merged: args=[message] with extra keys on log object', () => {
it('formats message from args when message not provided (template + params)', () => {
sentryReporter.log({
type: 'log',
level: 2,
args: ['Hello', 'world', { some: 'obj' }],
userId: 123,
action: 'login',
time: '2026-02-24T10:24:04.477Z',
smallObj: { firstLevel: { secondLevel: { thirdLevel: { fourthLevel: 'deep' } } } },
tag: '',
type: 'info',
args: ['Hello', 'world', 123, { key: 'value' }],
});

expect(formatConsoleArgs).toHaveBeenCalledWith(['Hello', 'world', 123, { key: 'value' }], 3, 1000);
const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0];

// Message from args
expect(call.message).toBe('Hello world {"some":"obj"}');
expect(call.attributes).toMatchObject({
'consola.type': 'log',
'consola.level': 2,
userId: 123,
smallObj: { firstLevel: { secondLevel: { thirdLevel: '[Object]' } } }, // Object is normalized
action: 'login',
time: '2026-02-24T10:24:04.477Z',
'sentry.origin': 'auto.log.consola',
});
expect(call.attributes?.['sentry.message.parameter.0']).toBeUndefined();
expect(call.level).toBe('info');
expect(call.message).toContain('Hello');
expect(call.attributes?.['sentry.message.template']).toBe('Hello {} {} {}');
expect(call.attributes?.['sentry.message.parameter.0']).toBe('world');
expect(call.attributes?.['sentry.message.parameter.1']).toBe(123);
expect(call.attributes?.['sentry.message.parameter.2']).toEqual({ key: 'value' });
});

it('capturing custom keys mimicking direct reporter.log({ type, message, userId, sessionId })', () => {
it('Uses "message" key as fallback message, when no args are available', () => {
sentryReporter.log({
type: 'info',
message: 'User action',
Expand Down