@sentry/core
Version:
Base implementation for all Sentry JavaScript SDKs
163 lines (162 loc) • 5.94 kB
JavaScript
import { getClient } from "../currentScopes.js";
import { _INTERNAL_captureLog } from "../logs/internal.js";
import { createConsoleTemplateAttributes, formatConsoleArgs, hasConsoleSubstitutions } from "../logs/utils.js";
import { isPlainObject } from "../utils/is.js";
import { normalize } from "../utils/normalize.js";
import { SENTRY_ORIGIN } from "@sentry/conventions/attributes";
// src/integrations/consola.ts
const DEFAULT_CAPTURED_LEVELS = [
"trace",
"debug",
"info",
"warn",
"error",
"fatal"
];
/**
* Creates a new Sentry reporter for Consola that forwards logs to Sentry.
*
* **Note: This integration supports Consola v3.x only.** The reporter interface and log object structure
* may differ in other versions of Consola.
*
* @param options - Configuration options for the reporter.
* @returns A Consola reporter that can be added to consola instances.
*
* @example
* ```ts
* import * as Sentry from '@sentry/node';
* import { consola } from 'consola';
*
* Sentry.init({
* dsn: '__DSN__',
* });
*
* const sentryReporter = Sentry.createConsolaReporter({
* // Optional: filter levels to capture
* levels: ['error', 'warn', 'info'],
* });
*
* consola.addReporter(sentryReporter);
*
* // Now consola logs will be captured by Sentry
* consola.info('This will be sent to Sentry');
* consola.error('This error will also be sent to Sentry');
* ```
*/
function createConsolaReporter(options = {}) {
const levels = new Set(options.levels ?? DEFAULT_CAPTURED_LEVELS);
const providedClient = options.client;
return { log(logObj) {
const { type, level, message: consolaMessage, args, tag, date: _date, ...rest } = logObj;
const client = providedClient || getClient();
if (!client) return;
const logSeverityLevel = getLogSeverityLevel(type, level);
if (!levels.has(logSeverityLevel)) return;
const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = client.getOptions();
const attributes = {};
for (const [key, value] of Object.entries(rest)) attributes[key] = normalize(value, normalizeDepth, normalizeMaxBreadth);
attributes[SENTRY_ORIGIN] = "auto.log.consola";
if (tag) attributes["consola.tag"] = tag;
if (type) attributes["consola.type"] = type;
if (level != null && typeof level === "number") 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: extractionResult?.message || consolaMessage || args && formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth) || "",
attributes
});
} };
}
const CONSOLA_TYPE_TO_LOG_SEVERITY_LEVEL_MAP = {
silent: "trace",
fatal: "fatal",
error: "error",
warn: "warn",
log: "info",
info: "info",
success: "info",
fail: "error",
ready: "info",
start: "info",
box: "info",
debug: "debug",
trace: "trace",
verbose: "debug",
critical: "fatal",
notice: "info"
};
const CONSOLA_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP = {
0: "fatal",
1: "warn",
2: "info",
3: "info",
4: "debug",
5: "trace"
};
/**
* Determines the log severity level from Consola type and level.
*
* @param type - The Consola log type (e.g., 'error', 'warn', 'info')
* @param level - The Consola numeric log level (0-5) or null for some types like 'verbose'
* @returns The corresponding Sentry log severity level
*/
function getLogSeverityLevel(type, level) {
if (type === "verbose") return "debug";
if (type === "silent") return "trace";
if (type) {
const mappedLevel = CONSOLA_TYPE_TO_LOG_SEVERITY_LEVEL_MAP[type];
if (mappedLevel) return mappedLevel;
}
if (typeof level === "number") {
const mappedLevel = CONSOLA_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[level];
if (mappedLevel) return mappedLevel;
}
return "info";
}
/**
* Extracts structured attributes from console arguments. If the first argument is a plain object, its properties are extracted as attributes.
*/
function defaultExtractAttributes(args, normalizeDepth, normalizeMaxBreadth) {
if (!args?.length) return { message: "" };
const message = formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth);
const firstArg = args[0];
if (isPlainObject(firstArg)) {
const remainingArgsStartIndex = typeof args[1] === "string" ? 2 : 1;
return {
message,
attributes: firstArg,
messageParameters: args.slice(remainingArgsStartIndex)
};
} else {
const followingArgs = args.slice(1);
const shouldAddTemplateAttr = followingArgs.length > 0 && typeof firstArg === "string" && !hasConsoleSubstitutions(firstArg);
return {
message,
messageTemplate: shouldAddTemplateAttr ? firstArg : void 0,
messageParameters: shouldAddTemplateAttr ? followingArgs : void 0
};
}
}
/**
* Processes extracted attributes by normalizing them and preparing message parameter attributes if a template is present.
*/
function processExtractedAttributes(extractionResult, normalizeDepth, normalizeMaxBreadth) {
const { message, attributes, messageTemplate, messageParameters } = extractionResult;
const messageParamAttributes = {};
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,
attributes: {
...normalize(attributes, normalizeDepth, normalizeMaxBreadth),
...messageParamAttributes
}
};
}
export { createConsolaReporter };
//# sourceMappingURL=consola.js.map