strogger
Version:
📊 A modern structured logging library with functional programming, duck-typing, and comprehensive third-party integrations
106 lines • 3.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLogFilter = exports.createSampler = exports.createRateLimiter = void 0;
/**
* Creates a rate limiter using token bucket algorithm
*/
const createRateLimiter = (maxLogsPerSecond, burstSize) => {
const state = {
tokens: burstSize,
lastRefill: Date.now(),
maxTokens: burstSize,
refillRate: maxLogsPerSecond,
};
const refillTokens = () => {
const now = Date.now();
const timePassed = (now - state.lastRefill) / 1000; // Convert to seconds
const tokensToAdd = timePassed * state.refillRate;
state.tokens = Math.min(state.maxTokens, state.tokens + tokensToAdd);
state.lastRefill = now;
};
const tryConsume = (tokens = 1) => {
refillTokens();
if (state.tokens >= tokens) {
state.tokens -= tokens;
return true;
}
return false;
};
return {
tryConsume,
getState: () => ({ ...state }),
};
};
exports.createRateLimiter = createRateLimiter;
/**
* Creates a sampling function that respects the sampling rate
*/
const createSampler = (samplingRate) => {
const state = {
totalLogs: 0,
sampledLogs: 0,
};
const shouldSample = () => {
state.totalLogs++;
if (samplingRate >= 1.0) {
state.sampledLogs++;
return true;
}
if (samplingRate <= 0.0) {
return false;
}
const random = Math.random();
if (random <= samplingRate) {
state.sampledLogs++;
return true;
}
return false;
};
const getStats = () => ({
totalLogs: state.totalLogs,
sampledLogs: state.sampledLogs,
samplingRate: state.totalLogs > 0 ? state.sampledLogs / state.totalLogs : 0,
configuredRate: samplingRate,
});
return {
shouldSample,
getStats,
};
};
exports.createSampler = createSampler;
/**
* Creates a combined sampling and rate limiting function
*/
const createLogFilter = (config) => {
const rateLimiter = config.rateLimit
? (0, exports.createRateLimiter)(config.rateLimit.maxLogsPerSecond, config.rateLimit.burstSize)
: null;
const sampler = config.samplingRate !== undefined
? (0, exports.createSampler)(config.samplingRate)
: null;
const shouldLog = () => {
// If no sampling or rate limiting is configured, always allow
if (!rateLimiter && !sampler) {
return true;
}
// Check rate limiting first
if (rateLimiter && !rateLimiter.tryConsume()) {
return false;
}
// Then check sampling
if (sampler && !sampler.shouldSample()) {
return false;
}
return true;
};
const getStats = () => ({
rateLimit: rateLimiter?.getState(),
sampling: sampler?.getStats(),
});
return {
shouldLog,
getStats,
};
};
exports.createLogFilter = createLogFilter;
//# sourceMappingURL=sampling.js.map