-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(consola): Enhance Consola integration to extract first-param object as searchable attributes #19534
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
Open
s1gr1d
wants to merge
4
commits into
develop
Choose a base branch
from
sig/consola-obj-keys
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+462
−25
Open
feat(consola): Enhance Consola integration to extract first-param object as searchable attributes #19534
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
28 changes: 28 additions & 0 deletions
28
dev-packages/node-integration-tests/suites/consola/subject-object-first.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,35 @@ | ||
| 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 { | ||
| /** | ||
| * 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. | ||
|
|
@@ -61,8 +88,9 @@ export interface ConsolaReporter { | |
| */ | ||
| export interface ConsolaLogObject { | ||
| /** | ||
| * Allows additional custom properties to be set on the log object. | ||
| * These properties will be captured as log attributes with a 'consola.' prefix. | ||
| * Allows additional custom properties to be set on the log object. These properties will be captured as log attributes. | ||
| * | ||
| * Additional properties are set when passing a single object with a `message` (`consola.[type]({ message: '', ... })`) or if the reporter is called directly | ||
| * | ||
| * @example | ||
| * ```ts | ||
|
|
@@ -73,7 +101,7 @@ export interface ConsolaLogObject { | |
| * userId: 123, | ||
| * sessionId: 'abc-123' | ||
| * }); | ||
| * // Will create attributes: consola.userId and consola.sessionId | ||
| * // Will create attributes: `userId` and `sessionId` | ||
| * ``` | ||
| */ | ||
| [key: string]: unknown; | ||
|
|
@@ -123,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 | ||
|
|
@@ -152,6 +180,10 @@ export interface ConsolaLogObject { | |
| * | ||
| * When provided, this is the final formatted message. When not provided, | ||
| * the message should be constructed from the `args` array. | ||
| * | ||
| * Note: In reporters, `message` is typically undefined. It is primarily for | ||
| * `consola.[type]({ message: 'xxx' })` usage and is normalized into `args` before | ||
| * reporters receive the log object. See: https://github.com/unjs/consola/issues/406#issuecomment-3684792551 | ||
| */ | ||
| message?: string; | ||
| } | ||
|
|
@@ -194,8 +226,9 @@ export function createConsolaReporter(options: ConsolaReporterOptions = {}): Con | |
|
|
||
| return { | ||
| log(logObj: ConsolaLogObject) { | ||
| // We need to exclude certain known properties from being added as additional attributes | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| const { type, level, message: consolaMessage, args, tag, date: _date, ...attributes } = logObj; | ||
| const { type, level, message: consolaMessage, args, tag, date: _date, ...rest } = logObj; | ||
|
|
||
| // Get client - use provided client or current client | ||
| const client = providedClient || getClient(); | ||
|
|
@@ -213,17 +246,13 @@ 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 | ||
| for (const [key, value] of Object.entries(rest)) { | ||
| attributes[key] = normalize(value, normalizeDepth, normalizeMaxBreadth); | ||
| } | ||
|
|
||
| attributes['sentry.origin'] = 'auto.log.consola'; | ||
|
|
||
| if (tag) { | ||
|
|
@@ -239,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, | ||
| }); | ||
| }, | ||
|
|
@@ -317,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( | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
| 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); | ||
s1gr1d marked this conversation as resolved.
Show resolved
Hide 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), | ||
| ...messageParamAttributes, | ||
| }, | ||
| }; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.