Skip to content

Commit c4b6d2d

Browse files
committed
feat(buffer): Add beforeSendLogs for sampling decisions
1 parent bbb1698 commit c4b6d2d

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

packages/core/src/log.ts

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { getActiveSpan } from './utils/spanUtils';
1212
const LOG_BUFFER_MAX_LENGTH = 25;
1313

1414
let GLOBAL_LOG_BUFFER: Log[] = [];
15+
let GLOBAL_LOG_BUFFER_INDEX = 0;
1516

1617
let isFlushingLogs = false;
1718

@@ -89,28 +90,36 @@ function addToLogBuffer(client: Client, log: Log, scope: Scope): void {
8990
void client.sendEnvelope(envelope);
9091
}
9192

92-
function sendAndClearLogs(): void {
93-
if (GLOBAL_LOG_BUFFER.length > 0) {
93+
if (GLOBAL_LOG_BUFFER.length >= LOG_BUFFER_MAX_LENGTH) {
94+
const shouldSendLogs = client.getOptions()?._experiments?.shouldSendLogs;
95+
if(!shouldSendLogs || shouldSendLogs?.(GLOBAL_LOG_BUFFER, true)) { // TODO: implement error tracking
9496
sendLogs(GLOBAL_LOG_BUFFER);
95-
GLOBAL_LOG_BUFFER = [];
97+
GLOBAL_LOG_BUFFER.length = 0;
98+
} else {
99+
// we should not send the logs buffer, evict a single log to make space for this one.
100+
GLOBAL_LOG_BUFFER[GLOBAL_LOG_BUFFER_INDEX] = log;
101+
GLOBAL_LOG_BUFFER_INDEX = (GLOBAL_LOG_BUFFER_INDEX + 1) % LOG_BUFFER_MAX_LENGTH;
96102
}
97-
}
98-
99-
if (GLOBAL_LOG_BUFFER.length >= LOG_BUFFER_MAX_LENGTH) {
100-
sendAndClearLogs();
101103
} else {
102104
GLOBAL_LOG_BUFFER.push(log);
103105
}
104106

105107
// this is the first time logs have been enabled, let's kick off an interval to flush them
106108
// we should only do this once.
107109
if (!isFlushingLogs) {
110+
const tryFlushLogs = (): void => {
111+
const shouldSendLogs = client.getOptions()?._experiments?.shouldSendLogs;
112+
if (!shouldSendLogs || shouldSendLogs?.(GLOBAL_LOG_BUFFER, true)) { // TODO: implement error tracking
113+
sendLogs(GLOBAL_LOG_BUFFER);
114+
GLOBAL_LOG_BUFFER.length = 0;
115+
}
116+
}
108117
client.on('flush', () => {
109-
sendAndClearLogs();
118+
tryFlushLogs();
110119
});
111120

112121
const flushTimer = setInterval(() => {
113-
sendAndClearLogs();
122+
tryFlushLogs();
114123
}, 5000);
115124

116125
// We need to unref the timer in node.js, otherwise the node process never exit.

0 commit comments

Comments
 (0)