Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import * as Sentry from '@sentry/node';
import { loggingTransport } from '@sentry-internal/node-integration-tests';
import { consola } from 'consola';

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
release: '1.0.0',
environment: 'test',
enableLogs: true,
transport: loggingTransport,
});

async function run(): Promise<void> {
consola.level = 5;
const sentryReporter = Sentry.createConsolaReporter();
consola.addReporter(sentryReporter);

// Object-first: args = [object, string] — first object becomes attributes, second arg is part of formatted message
consola.info({ userId: 100, action: 'login' }, 'User logged in');

// Object-first: args = [object] only — object keys become attributes, message is stringified object
consola.info({ event: 'click', count: 2 });

await Sentry.flush();
}

// eslint-disable-next-line @typescript-eslint/no-floating-promises
void run();
51 changes: 51 additions & 0 deletions dev-packages/node-integration-tests/suites/consola/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -491,4 +491,55 @@ describe('consola integration', () => {

await runner.completed();
});

test('should capture object-first consola logs (object as first arg)', async () => {
const runner = createRunner(__dirname, 'subject-object-first.ts')
.expect({
log: {
items: [
{
timestamp: expect.any(Number),
level: 'info',
body: '{"userId":100,"action":"login"} User logged in',
severity_number: expect.any(Number),
trace_id: expect.any(String),
attributes: {
'sentry.origin': { value: 'auto.log.consola', type: 'string' },
'sentry.release': { value: '1.0.0', type: 'string' },
'sentry.environment': { value: 'test', type: 'string' },
'sentry.sdk.name': { value: 'sentry.javascript.node', type: 'string' },
'sentry.sdk.version': { value: expect.any(String), type: 'string' },
'server.address': { value: expect.any(String), type: 'string' },
'consola.type': { value: 'info', type: 'string' },
'consola.level': { value: 3, type: 'integer' },
userId: { value: 100, type: 'integer' },
action: { value: 'login', type: 'string' },
},
},
{
timestamp: expect.any(Number),
level: 'info',
body: '{"event":"click","count":2}',
severity_number: expect.any(Number),
trace_id: expect.any(String),
attributes: {
'sentry.origin': { value: 'auto.log.consola', type: 'string' },
'sentry.release': { value: '1.0.0', type: 'string' },
'sentry.environment': { value: 'test', type: 'string' },
'sentry.sdk.name': { value: 'sentry.javascript.node', type: 'string' },
'sentry.sdk.version': { value: expect.any(String), type: 'string' },
'server.address': { value: expect.any(String), type: 'string' },
'consola.type': { value: 'info', type: 'string' },
'consola.level': { value: 3, type: 'integer' },
event: { value: 'click', type: 'string' },
count: { value: 2, type: 'integer' },
},
},
],
},
})
.start();

await runner.completed();
});
});
134 changes: 121 additions & 13 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.
*/
interface ExtractAttributesResult {
/**
* 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 @@ -125,7 +151,7 @@ export interface ConsolaLogObject {
/**
* The raw arguments passed to the log method.
*
* These args are typically formatted into the final `message`. In Consola reporters, `message` is not provided.
* These args are typically formatted into the final `message`. In Consola reporters, `message` is not provided. See: https://github.com/unjs/consola/issues/406#issuecomment-3684792551
*
* @example
* ```ts
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
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 shouldAddTemplateAttr =
followingArgs.length > 0 && typeof firstArg === 'string' && !hasConsoleSubstitutions(firstArg);

return {
message,
messageTemplate: shouldAddTemplateAttr ? firstArg : undefined,
messageParameters: shouldAddTemplateAttr ? 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),
Copy link

Choose a reason for hiding this comment

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

Object-first attributes normalized one level shallower than rest

Medium Severity

normalize(attributes, normalizeDepth, normalizeMaxBreadth) normalizes the entire extracted attributes object as one entity, consuming one depth level for the container. This means each attribute value effectively gets normalizeDepth - 1 levels. In contrast, rest attributes (line 252–254) are normalized per-value with the full normalizeDepth. With the default depth of 3, object-first attribute values get only 2 effective levels — a silent 33% reduction that causes unexpected data truncation for moderately nested objects.

Fix in Cursor Fix in Web

Triggered by project rule: PR Review Guidelines for Cursor Bot

...messageParamAttributes,
},
};
}
Loading
Loading