@sentry/core
Version:
Base implementation for all Sentry JavaScript SDKs
196 lines (195 loc) • 9.27 kB
JavaScript
import { serializeAttributes } from "../attributes.js";
import { getGlobalSingleton } from "../carrier.js";
import { getClient, getCurrentScope, getIsolationScope } from "../currentScopes.js";
import { DEBUG_BUILD } from "../debug-build.js";
import { consoleSandbox, debug } from "../utils/debug-logger.js";
import { isParameterizedString } from "../utils/is.js";
import { CALLBACK_ERROR, safeCallback } from "../utils/safeCallback.js";
import { getCombinedScopeData } from "../utils/scopeData.js";
import { getActiveSpan } from "../utils/spanUtils.js";
import { timestampInSeconds } from "../utils/time.js";
import { getSequenceAttribute } from "../utils/timestampSequence.js";
import { _getTraceInfoFromScope } from "../utils/trace-info.js";
import { estimateLogSizeInBytes, setupWeightBasedFlushing } from "../utils/weightBasedFlushing.js";
import { SEVERITY_TEXT_TO_SEVERITY_NUMBER } from "./constants.js";
import { createLogEnvelope } from "./envelope.js";
import { SENTRY_ENVIRONMENT, SENTRY_MESSAGE_TEMPLATE, SENTRY_RELEASE, SENTRY_REPLAY_ID, SENTRY_SDK_NAME, SENTRY_SDK_VERSION, SENTRY_TRACE_PARENT_SPAN_ID, USER_EMAIL, USER_ID, USER_NAME } from "@sentry/conventions/attributes";
// src/logs/internal.ts
const MAX_LOG_BUFFER_SIZE = 100;
/**
* Sets a log attribute if the value exists and the attribute key is not already present.
*
* @param logAttributes - The log attributes object to modify.
* @param key - The attribute key to set.
* @param value - The value to set (only sets if truthy and key not present).
* @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.
*/
function setLogAttribute(logAttributes, key, value, setEvenIfPresent = true) {
if (value && (!logAttributes[key] || setEvenIfPresent)) logAttributes[key] = value;
}
/**
* Captures a serialized log event and adds it to the log buffer for the given client.
*
* @param client - A client. Uses the current client if not provided.
* @param serializedLog - The serialized log event to capture.
*
* @experimental This method will experience breaking changes. This is not yet part of
* the stable Sentry SDK API and can be changed or removed without warning.
*/
function _INTERNAL_captureSerializedLog(client, serializedLog) {
const bufferMap = _getBufferMap();
const logBuffer = _INTERNAL_getLogBuffer(client);
if (logBuffer === void 0) {
setupWeightBasedFlushing(client, "afterCaptureLog", "flushLogs", estimateLogSizeInBytes, _INTERNAL_flushLogsBuffer);
bufferMap.set(client, [serializedLog]);
} else if (logBuffer.length >= MAX_LOG_BUFFER_SIZE) {
_INTERNAL_flushLogsBuffer(client, logBuffer);
bufferMap.set(client, [serializedLog]);
} else bufferMap.set(client, [...logBuffer, serializedLog]);
}
/**
* Captures a log event and sends it to Sentry.
*
* @param log - The log event to capture.
* @param scope - A scope. Uses the current scope if not provided.
* @param client - A client. Uses the current client if not provided.
* @param captureSerializedLog - A function to capture the serialized log.
*
* @experimental This method will experience breaking changes. This is not yet part of
* the stable Sentry SDK API and can be changed or removed without warning.
*/
function _INTERNAL_captureLog(beforeLog, currentScope = getCurrentScope(), captureSerializedLog = _INTERNAL_captureSerializedLog) {
const client = currentScope?.getClient() ?? getClient();
if (!client) {
DEBUG_BUILD && debug.warn("No client available to capture log.");
return;
}
const { release, environment, beforeSendLog } = client.getOptions();
const [, traceContext] = _getTraceInfoFromScope(client, currentScope);
const processedLogAttributes = { ...beforeLog.attributes };
const { user: { id, email, username }, attributes: scopeAttributes } = getCombinedScopeData(getIsolationScope(), currentScope);
setLogAttribute(processedLogAttributes, USER_ID, id, false);
setLogAttribute(processedLogAttributes, USER_EMAIL, email, false);
setLogAttribute(processedLogAttributes, USER_NAME, username, false);
setLogAttribute(processedLogAttributes, SENTRY_RELEASE, release);
setLogAttribute(processedLogAttributes, SENTRY_ENVIRONMENT, environment);
const { name, version } = client.getSdkMetadata()?.sdk ?? {};
setLogAttribute(processedLogAttributes, SENTRY_SDK_NAME, name);
setLogAttribute(processedLogAttributes, SENTRY_SDK_VERSION, version);
const replay = client.getIntegrationByName("Replay");
const replayId = replay?.getReplayId(true);
setLogAttribute(processedLogAttributes, SENTRY_REPLAY_ID, replayId);
if (replayId && replay?.getRecordingMode() === "buffer") setLogAttribute(processedLogAttributes, "sentry._internal.replay_is_buffering", true);
const beforeLogMessage = beforeLog.message;
if (isParameterizedString(beforeLogMessage)) {
const { __sentry_template_string__, __sentry_template_values__ = [] } = beforeLogMessage;
if (__sentry_template_values__?.length) processedLogAttributes[SENTRY_MESSAGE_TEMPLATE] = __sentry_template_string__;
__sentry_template_values__.forEach((param, index) => {
processedLogAttributes[`sentry.message.parameter.${index}`] = param;
});
}
const span = getActiveSpan(currentScope);
setLogAttribute(processedLogAttributes, SENTRY_TRACE_PARENT_SPAN_ID, span?.spanContext().spanId);
const processedLog = {
...beforeLog,
attributes: processedLogAttributes
};
client.emit("beforeCaptureLog", processedLog);
const log = beforeSendLog ? safeCallback(DEBUG_BUILD ? "The `beforeSendLog` callback threw an error, dropping the log:" : "", () => consoleSandbox(() => beforeSendLog(processedLog)), () => CALLBACK_ERROR) : processedLog;
if (log === CALLBACK_ERROR) {
client.recordDroppedEvent("callback_error", "log_item", 1);
return;
}
if (!log) {
client.recordDroppedEvent("before_send", "log_item", 1);
DEBUG_BUILD && debug.warn("beforeSendLog returned null, log will not be captured.");
return;
}
const { level, message, attributes: logAttributes = {}, severityNumber } = log;
const timestamp = timestampInSeconds();
const sequenceAttr = getSequenceAttribute(timestamp);
captureSerializedLog(client, {
timestamp,
level,
body: _removeLoneSurrogates(String(message)),
trace_id: traceContext?.trace_id,
severity_number: severityNumber ?? SEVERITY_TEXT_TO_SEVERITY_NUMBER[level],
attributes: sanitizeLogAttributes({
...serializeAttributes(scopeAttributes),
...serializeAttributes(logAttributes, true),
[sequenceAttr.key]: sequenceAttr.value
})
});
client.emit("afterCaptureLog", log);
}
/**
* Flushes the logs buffer to Sentry.
*
* @param client - A client.
* @param maybeLogBuffer - A log buffer. Uses the log buffer for the given client if not provided.
*
* @experimental This method will experience breaking changes. This is not yet part of
* the stable Sentry SDK API and can be changed or removed without warning.
*/
function _INTERNAL_flushLogsBuffer(client, maybeLogBuffer) {
const logBuffer = maybeLogBuffer ?? _INTERNAL_getLogBuffer(client) ?? [];
if (logBuffer.length === 0) return;
const clientOptions = client.getOptions();
const envelope = createLogEnvelope(logBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn(), client.getDataCollectionOptions().userInfo);
_getBufferMap().set(client, []);
client.emit("flushLogs");
client.sendEnvelope(envelope);
}
/**
* Returns the log buffer for a given client.
*
* Exported for testing purposes.
*
* @param client - The client to get the log buffer for.
* @returns The log buffer for the given client.
*/
function _INTERNAL_getLogBuffer(client) {
return _getBufferMap().get(client);
}
function _getBufferMap() {
return getGlobalSingleton("clientToLogBufferMap", () => /* @__PURE__ */ new WeakMap());
}
/**
* Sanitizes serialized log attributes by replacing lone surrogates in both
* keys and string values with U+FFFD.
*/
function sanitizeLogAttributes(attributes) {
const sanitized = {};
for (const [key, attr] of Object.entries(attributes)) {
const sanitizedKey = _removeLoneSurrogates(key);
if (attr.type === "string") sanitized[sanitizedKey] = {
...attr,
value: _removeLoneSurrogates(attr.value)
};
else sanitized[sanitizedKey] = attr;
}
return sanitized;
}
/**
* Replaces unpaired UTF-16 surrogates with U+FFFD (replacement character).
*
* Lone surrogates (U+D800–U+DFFF not part of a valid pair) cause `serde_json`
* on the server to reject the entire log batch when they appear in
* JSON-escaped form (e.g. `\uD800`). Replacing them at the SDK level ensures
* only the offending characters are lost instead of the whole payload.
*
* Uses the native `String.prototype.toWellFormed()` when available
* (Node 20+, Chrome 111+, Safari 15.4+, Firefox 119+, Hermes).
* On older runtimes without native support, returns the string as-is.
*
* Exported for testing
*/
function _removeLoneSurrogates(str) {
const strObj = Object(str);
const isWellFormed = strObj["isWellFormed"];
const toWellFormed = strObj["toWellFormed"];
if (typeof isWellFormed === "function" && typeof toWellFormed === "function") return isWellFormed.call(str) ? str : toWellFormed.call(str);
return str;
}
export { _INTERNAL_captureLog, _INTERNAL_captureSerializedLog, _INTERNAL_flushLogsBuffer, _INTERNAL_getLogBuffer, _removeLoneSurrogates };
//# sourceMappingURL=internal.js.map