advanced-logger
Version:
Advanced logger module extendable with plugins. Works in nodejs and browsers
964 lines (929 loc) • 27.9 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// node_modules/fast-safe-stringify/index.js
var require_fast_safe_stringify = __commonJS({
"node_modules/fast-safe-stringify/index.js"(exports2, module2) {
"use strict";
module2.exports = stringify2;
stringify2.default = stringify2;
stringify2.stable = deterministicStringify;
stringify2.stableStringify = deterministicStringify;
var LIMIT_REPLACE_NODE = "[...]";
var CIRCULAR_REPLACE_NODE = "[Circular]";
var arr = [];
var replacerStack = [];
function defaultOptions() {
return {
depthLimit: Number.MAX_SAFE_INTEGER,
edgesLimit: Number.MAX_SAFE_INTEGER
};
}
function stringify2(obj, replacer, spacer, options) {
if (typeof options === "undefined") {
options = defaultOptions();
}
decirc(obj, "", 0, [], void 0, 0, options);
var res;
try {
if (replacerStack.length === 0) {
res = JSON.stringify(obj, replacer, spacer);
} else {
res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);
}
} catch (_) {
return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]");
} finally {
while (arr.length !== 0) {
var part = arr.pop();
if (part.length === 4) {
Object.defineProperty(part[0], part[1], part[3]);
} else {
part[0][part[1]] = part[2];
}
}
}
return res;
}
function setReplace(replace, val, k, parent) {
var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);
if (propertyDescriptor.get !== void 0) {
if (propertyDescriptor.configurable) {
Object.defineProperty(parent, k, { value: replace });
arr.push([parent, k, val, propertyDescriptor]);
} else {
replacerStack.push([val, k, replace]);
}
} else {
parent[k] = replace;
arr.push([parent, k, val]);
}
}
function decirc(val, k, edgeIndex, stack, parent, depth, options) {
depth += 1;
var i;
if (typeof val === "object" && val !== null) {
for (i = 0; i < stack.length; i++) {
if (stack[i] === val) {
setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);
return;
}
}
if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) {
setReplace(LIMIT_REPLACE_NODE, val, k, parent);
return;
}
if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) {
setReplace(LIMIT_REPLACE_NODE, val, k, parent);
return;
}
stack.push(val);
if (Array.isArray(val)) {
for (i = 0; i < val.length; i++) {
decirc(val[i], i, i, stack, val, depth, options);
}
} else {
var keys = Object.keys(val);
for (i = 0; i < keys.length; i++) {
var key = keys[i];
decirc(val[key], key, i, stack, val, depth, options);
}
}
stack.pop();
}
}
function compareFunction(a, b) {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
function deterministicStringify(obj, replacer, spacer, options) {
if (typeof options === "undefined") {
options = defaultOptions();
}
var tmp = deterministicDecirc(obj, "", 0, [], void 0, 0, options) || obj;
var res;
try {
if (replacerStack.length === 0) {
res = JSON.stringify(tmp, replacer, spacer);
} else {
res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer);
}
} catch (_) {
return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]");
} finally {
while (arr.length !== 0) {
var part = arr.pop();
if (part.length === 4) {
Object.defineProperty(part[0], part[1], part[3]);
} else {
part[0][part[1]] = part[2];
}
}
}
return res;
}
function deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) {
depth += 1;
var i;
if (typeof val === "object" && val !== null) {
for (i = 0; i < stack.length; i++) {
if (stack[i] === val) {
setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);
return;
}
}
try {
if (typeof val.toJSON === "function") {
return;
}
} catch (_) {
return;
}
if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) {
setReplace(LIMIT_REPLACE_NODE, val, k, parent);
return;
}
if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) {
setReplace(LIMIT_REPLACE_NODE, val, k, parent);
return;
}
stack.push(val);
if (Array.isArray(val)) {
for (i = 0; i < val.length; i++) {
deterministicDecirc(val[i], i, i, stack, val, depth, options);
}
} else {
var tmp = {};
var keys = Object.keys(val).sort(compareFunction);
for (i = 0; i < keys.length; i++) {
var key = keys[i];
deterministicDecirc(val[key], key, i, stack, val, depth, options);
tmp[key] = val[key];
}
if (typeof parent !== "undefined") {
arr.push([parent, k, val]);
parent[k] = tmp;
} else {
return tmp;
}
}
stack.pop();
}
}
function replaceGetterValues(replacer) {
replacer = typeof replacer !== "undefined" ? replacer : function(k, v) {
return v;
};
return function(key, val) {
if (replacerStack.length > 0) {
for (var i = 0; i < replacerStack.length; i++) {
var part = replacerStack[i];
if (part[1] === key && part[0] === val) {
val = part[2];
replacerStack.splice(i, 1);
break;
}
}
}
return replacer.call(this, key, val);
};
}
}
});
// src/index.ts
var src_exports = {};
__export(src_exports, {
AdvancedLogger: () => AdvancedLogger,
TransformationEnum: () => TransformationEnum,
service: () => service,
strategy: () => strategy
});
module.exports = __toCommonJS(src_exports);
// src/util/EventEmitter.ts
var EventEmitter = class {
constructor() {
this.listeners = /* @__PURE__ */ new Map();
}
on(event, fn) {
(this.listeners.get(event) ?? this.set(event)).add(fn);
return this;
}
once(event, fn) {
const wrap = (...args) => {
this.off(event, wrap);
fn(...args);
};
return this.on(event, wrap);
}
off(event, fn) {
this.listeners.get(event)?.delete(fn);
return this;
}
removeListener(event, fn) {
return this.off(event, fn);
}
emit(event, ...args) {
const set = this.listeners.get(event);
if (!set || set.size === 0) {
return false;
}
for (const fn of [...set]) {
fn(...args);
}
return true;
}
removeAllListeners(event) {
if (event) {
this.listeners.delete(event);
} else {
this.listeners.clear();
}
return this;
}
set(event) {
const s = /* @__PURE__ */ new Set();
this.listeners.set(event, s);
return s;
}
};
// node_modules/lodash-es/isObject.js
function isObject(value) {
var type = typeof value;
return value != null && (type == "object" || type == "function");
}
var isObject_default = isObject;
// node_modules/lodash-es/_freeGlobal.js
var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
var freeGlobal_default = freeGlobal;
// node_modules/lodash-es/_root.js
var freeSelf = typeof self == "object" && self && self.Object === Object && self;
var root = freeGlobal_default || freeSelf || Function("return this")();
var root_default = root;
// node_modules/lodash-es/now.js
var now = function() {
return root_default.Date.now();
};
var now_default = now;
// node_modules/lodash-es/_trimmedEndIndex.js
var reWhitespace = /\s/;
function trimmedEndIndex(string) {
var index = string.length;
while (index-- && reWhitespace.test(string.charAt(index))) {
}
return index;
}
var trimmedEndIndex_default = trimmedEndIndex;
// node_modules/lodash-es/_baseTrim.js
var reTrimStart = /^\s+/;
function baseTrim(string) {
return string ? string.slice(0, trimmedEndIndex_default(string) + 1).replace(reTrimStart, "") : string;
}
var baseTrim_default = baseTrim;
// node_modules/lodash-es/_Symbol.js
var Symbol2 = root_default.Symbol;
var Symbol_default = Symbol2;
// node_modules/lodash-es/_getRawTag.js
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
var nativeObjectToString = objectProto.toString;
var symToStringTag = Symbol_default ? Symbol_default.toStringTag : void 0;
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
try {
value[symToStringTag] = void 0;
var unmasked = true;
} catch (e) {
}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
var getRawTag_default = getRawTag;
// node_modules/lodash-es/_objectToString.js
var objectProto2 = Object.prototype;
var nativeObjectToString2 = objectProto2.toString;
function objectToString(value) {
return nativeObjectToString2.call(value);
}
var objectToString_default = objectToString;
// node_modules/lodash-es/_baseGetTag.js
var nullTag = "[object Null]";
var undefinedTag = "[object Undefined]";
var symToStringTag2 = Symbol_default ? Symbol_default.toStringTag : void 0;
function baseGetTag(value) {
if (value == null) {
return value === void 0 ? undefinedTag : nullTag;
}
return symToStringTag2 && symToStringTag2 in Object(value) ? getRawTag_default(value) : objectToString_default(value);
}
var baseGetTag_default = baseGetTag;
// node_modules/lodash-es/isObjectLike.js
function isObjectLike(value) {
return value != null && typeof value == "object";
}
var isObjectLike_default = isObjectLike;
// node_modules/lodash-es/isSymbol.js
var symbolTag = "[object Symbol]";
function isSymbol(value) {
return typeof value == "symbol" || isObjectLike_default(value) && baseGetTag_default(value) == symbolTag;
}
var isSymbol_default = isSymbol;
// node_modules/lodash-es/toNumber.js
var NAN = 0 / 0;
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
var reIsBinary = /^0b[01]+$/i;
var reIsOctal = /^0o[0-7]+$/i;
var freeParseInt = parseInt;
function toNumber(value) {
if (typeof value == "number") {
return value;
}
if (isSymbol_default(value)) {
return NAN;
}
if (isObject_default(value)) {
var other = typeof value.valueOf == "function" ? value.valueOf() : value;
value = isObject_default(other) ? other + "" : other;
}
if (typeof value != "string") {
return value === 0 ? value : +value;
}
value = baseTrim_default(value);
var isBinary = reIsBinary.test(value);
return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
var toNumber_default = toNumber;
// node_modules/lodash-es/debounce.js
var FUNC_ERROR_TEXT = "Expected a function";
var nativeMax = Math.max;
var nativeMin = Math.min;
function debounce(func, wait, options) {
var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
if (typeof func != "function") {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber_default(wait) || 0;
if (isObject_default(options)) {
leading = !!options.leading;
maxing = "maxWait" in options;
maxWait = maxing ? nativeMax(toNumber_default(options.maxWait) || 0, wait) : maxWait;
trailing = "trailing" in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs, thisArg = lastThis;
lastArgs = lastThis = void 0;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
lastInvokeTime = time;
timerId = setTimeout(timerExpired, wait);
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
}
function timerExpired() {
var time = now_default();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = void 0;
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = void 0;
return result;
}
function cancel() {
if (timerId !== void 0) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = void 0;
}
function flush() {
return timerId === void 0 ? result : trailingEdge(now_default());
}
function debounced() {
var time = now_default(), isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === void 0) {
return leadingEdge(lastCallTime);
}
if (maxing) {
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === void 0) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
var debounce_default = debounce;
// node_modules/lodash-es/throttle.js
var FUNC_ERROR_TEXT2 = "Expected a function";
function throttle(func, wait, options) {
var leading = true, trailing = true;
if (typeof func != "function") {
throw new TypeError(FUNC_ERROR_TEXT2);
}
if (isObject_default(options)) {
leading = "leading" in options ? !!options.leading : leading;
trailing = "trailing" in options ? !!options.trailing : trailing;
}
return debounce_default(func, wait, {
"leading": leading,
"maxWait": wait,
"trailing": trailing
});
}
var throttle_default = throttle;
// src/util/LogUtils.ts
var DELIMETER = "-";
var LogUtils_default = {
getLogIdByFields(log, fields) {
return fields.map((field) => `${field}${DELIMETER}${log[field]}`).join(DELIMETER);
},
/**
* It is necessary to convert objects safely, otherwise we can lost the whole log bundle
*/
tryJSONStringify(obj) {
try {
return JSON.stringify(obj);
} catch (_) {
return "";
}
}
};
// src/enums/TransformationEnum.ts
var TransformationEnum = /* @__PURE__ */ ((TransformationEnum2) => {
TransformationEnum2[TransformationEnum2["RAPID_FIRE_GROUPING"] = 0] = "RAPID_FIRE_GROUPING";
return TransformationEnum2;
})(TransformationEnum || {});
// src/LogStore.ts
var LogStore = class {
constructor(config) {
this.groupLeftIndex = -1;
this.logs = [];
this.eventEmitter = new EventEmitter();
this.config = config;
this.identityMap = /* @__PURE__ */ new Map();
if (this.config.transformations) {
const groupableConfig = this.config.transformations.find((value) => value.type === 0 /* RAPID_FIRE_GROUPING */);
if (groupableConfig) {
this.groupableConfig = groupableConfig.configuration;
this.throttledOnGroupFinalize = throttle_default(
this.onGroupFinalize.bind(this),
this.groupableConfig.interval,
{ trailing: true, leading: false }
);
this.eventEmitter.on("add", this.throttledOnGroupFinalize);
}
}
}
add(log) {
if (this.groupableConfig) {
const id = LogUtils_default.getLogIdByFields(log, this.groupableConfig.groupIdentityFields);
if (!this.identityMap.has(id)) {
this.logs.push(log);
}
this.onAddToGroup(log);
} else {
this.logs.push(log);
}
this.eventEmitter.emit("add", {
logCount: this.size()
});
}
clear() {
this.logs.length = 0;
this.eventEmitter.emit("clear");
}
getAll() {
if (this.throttledOnGroupFinalize) {
this.throttledOnGroupFinalize.flush();
}
return this.logs.slice();
}
size() {
return this.logs.length;
}
destroy() {
if (this.throttledOnGroupFinalize) {
this.throttledOnGroupFinalize.cancel();
}
this.logs.splice(0);
this.eventEmitter.removeAllListeners();
}
onAddToGroup(log) {
const logId = LogUtils_default.getLogIdByFields(log, this.groupableConfig.groupIdentityFields);
if (this.identityMap.has(logId)) {
const savedCounter = this.identityMap.get(logId);
this.identityMap.set(logId, (savedCounter || 0) + 1);
} else {
this.identityMap.set(logId, 1);
}
}
onGroupFinalize() {
const len = this.logs.length;
if (len > 0) {
for (let i = this.groupLeftIndex !== -1 ? this.groupLeftIndex : 0; i < len; i++) {
const log = this.logs[i];
const id = LogUtils_default.getLogIdByFields(log, this.groupableConfig.groupIdentityFields);
Object.assign(log, { [this.groupableConfig.groupFieldName]: this.identityMap.has(id) ? this.identityMap.get(id) : 1 });
}
}
this.groupLeftIndex = len > 0 ? len - 1 : -1;
this.identityMap.clear();
}
};
// src/AdvancedLogger.ts
var AdvancedLogger = class {
constructor(configuration) {
this.configuration = configuration;
this.logStore = new LogStore({ transformations: this.configuration.transformations });
this.strategy = this.configuration.strategy;
this.service = this.configuration.service;
this.logStore.eventEmitter.on("add", this.onAdd.bind(this));
this.logStore.eventEmitter.on("clear", this.onClear.bind(this));
this.logStore.eventEmitter.on("error", this.onStoreError.bind(this));
this.strategy.eventEmitter.on("send", this.onSend.bind(this));
this.strategy.eventEmitter.on("error", this.onStrategyError.bind(this));
}
log(log) {
this.logStore.add(log);
}
/**
* Forces strategy to initiate logs sending
*/
sendAllLogs() {
this.strategy.sendAll();
}
destroy() {
this.logStore.destroy();
this.strategy.destroy();
this.service.destroy();
}
onStoreError(error) {
console.error(error);
}
onAdd(info) {
this.strategy.onAdd(info);
}
onClear() {
this.strategy.onClear();
}
onStrategyError(error) {
console.error(error);
}
async onSend() {
if (this.logStore.size() > 0) {
const logs = this.logStore.getAll();
this.logStore.clear();
try {
await this.service.sendAllLogs(logs);
} catch (error) {
console.error(error);
}
}
}
};
// src/service/BaseRemoteService.ts
var import_fast_safe_stringify = __toESM(require_fast_safe_stringify());
// src/util/http.ts
var http = {
async request(serviceConfig, headers, payload) {
const response = await fetch(serviceConfig.url, {
method: serviceConfig.method,
headers,
body: payload
});
if (!response.ok) {
throw new Error(`Request to ${serviceConfig.url} failed with status ${response.status}`);
}
return response;
},
delayedRetry(retries, delay, fn) {
return new Promise((resolve, reject) => {
setTimeout(() => fn().then(resolve).catch(reject), delay);
}).catch((error) => retries > 1 ? http.delayedRetry(retries - 1, delay, fn) : Promise.reject(error));
}
};
var http_default = http;
// src/service/BaseRemoteService.ts
var BaseRemoteService = class {
constructor(config) {
this.serviceConfig = { ...config.serviceConfig };
this.defaultLogConfig = { ...config.defaultLogConfig };
if (config.serializer) {
this.serializer = config.serializer;
}
}
serializer(log) {
return LogUtils_default.tryJSONStringify(log) || (0, import_fast_safe_stringify.default)(log);
}
async sendAllLogs(logs) {
const payload = await this.preparePayload(logs);
const headers = this.getHeaders();
try {
return await http_default.request(this.serviceConfig, headers, payload);
} catch (error) {
if ((this.serviceConfig?.retryAttempts ?? 0) > 0) {
return http_default.delayedRetry(
this.serviceConfig?.retryAttempts ?? 0,
this.serviceConfig?.retryInterval ?? 0,
http_default.request.bind(this, this.serviceConfig, headers, payload)
);
} else {
throw error;
}
}
}
async preparePayload(logs) {
const resultList = logs.map((log) => this.serializer({ ...this.defaultLogConfig, ...log }));
return resultList.join("\n");
}
destroy() {
}
/**
* Returns object for headers config
* @example
* {"Content-Type": "text/plain"}
*/
getHeaders() {
return {};
}
};
// src/service/ConsoleService.ts
var ConsoleService = class {
async preparePayload(logs) {
return logs.map((log) => this.serializer(log));
}
async sendAllLogs(logs) {
console.log(logs);
}
destroy() {
}
serializer(log) {
return log;
}
};
// src/service/ElasticsearchService.ts
var DEFAULT_INDEX_FIELD = "Index";
var DEFAULT_INDEX_VALUE = "index";
var ElasticsearchService = class extends BaseRemoteService {
async preparePayload(logs) {
const resultList = [];
logs.forEach((log) => {
const finalLog = { ...this.defaultLogConfig, ...log };
resultList.push(this.serializer(this.getLogMetaConfig(
finalLog[this.serviceConfig.logMetaIndexField || DEFAULT_INDEX_FIELD]
)));
resultList.push(this.serializer(finalLog));
});
return `${resultList.join("\n")}
`;
}
getHeaders() {
return {
"Content-Type": "application/json"
};
}
getLogMetaConfig(index) {
return {
index: {
_index: index || DEFAULT_INDEX_VALUE,
_type: "_doc"
}
};
}
};
// src/service/LogglyService.ts
var LogglyService = class extends BaseRemoteService {
getHeaders() {
return {
"Content-Type": "text/plain"
};
}
};
// src/service/SumologicService.ts
var SumologicService = class extends BaseRemoteService {
getHeaders() {
const serviceConfig = this.serviceConfig;
return {
"Content-Type": "application/json",
//todo Optional?
"X-Sumo-Category": serviceConfig.sourceCategory,
//todo Optional?
"X-Sumo-Host": serviceConfig.host,
//todo Optional?
"X-Sumo-Name": serviceConfig.sourceName
};
}
};
// src/strategy/InstantStrategy.ts
var InstantStrategy = class {
constructor() {
this.eventEmitter = new EventEmitter();
}
onAdd(info) {
this.eventEmitter.emit("send");
}
onClear() {
}
sendAll() {
}
destroy() {
this.eventEmitter.removeAllListeners();
}
};
// src/strategy/OnBundleSizeStrategy.ts
var OnBundleSizeStrategy = class {
constructor(config) {
/**
* @type {number}
*/
this.MAX_BUNDLE_SIZE = 100;
this.eventEmitter = new EventEmitter();
if (config.maxBundle) {
this.MAX_BUNDLE_SIZE = config.maxBundle;
}
}
onAdd(info) {
if (info && info.logCount >= this.MAX_BUNDLE_SIZE) {
this.eventEmitter.emit("send");
} else {
}
}
onClear() {
}
sendAll() {
this.eventEmitter.emit("send");
}
destroy() {
this.eventEmitter.removeAllListeners();
}
};
// src/strategy/OnIntervalStrategy.ts
var OnIntervalStrategy = class {
constructor(config) {
this.SEND_INTERVAL = 15e3;
this.eventEmitter = new EventEmitter();
if (config.interval) {
this.SEND_INTERVAL = config.interval;
}
this.intervalSend = throttle_default(this.send.bind(this), this.SEND_INTERVAL, { leading: false, trailing: true });
}
onAdd(info) {
if (info && info.logCount > 0) {
this.intervalSend();
}
}
onClear() {
}
sendAll() {
this.eventEmitter.emit("send");
}
destroy() {
this.intervalSend.cancel();
this.eventEmitter.removeAllListeners();
}
send() {
this.eventEmitter.emit("send");
}
};
// src/strategy/OnRequestStrategy.ts
var OnRequestStrategy = class {
constructor() {
this.eventEmitter = new EventEmitter();
}
onAdd(info) {
}
onClear() {
}
sendAll() {
this.eventEmitter.emit("send");
}
destroy() {
this.eventEmitter.removeAllListeners();
}
};
// src/strategy/HybridStrategy.ts
var HybridStrategy = class {
constructor(config = {}) {
this.MAX_BUNDLE_SIZE = 100;
this.SEND_INTERVAL = 15e3;
this.eventEmitter = new EventEmitter();
if (config.maxBundle) {
this.MAX_BUNDLE_SIZE = config.maxBundle;
}
if (config.interval) {
this.SEND_INTERVAL = config.interval;
}
this.intervalSend = throttle_default(this.send.bind(this), this.SEND_INTERVAL, { leading: false, trailing: true });
}
onAdd(info) {
if (!info) {
return;
}
if (info.logCount >= this.MAX_BUNDLE_SIZE) {
this.intervalSend.cancel();
this.eventEmitter.emit("send");
} else if (info.logCount > 0) {
this.intervalSend();
}
}
onClear() {
}
sendAll() {
this.eventEmitter.emit("send");
}
destroy() {
this.intervalSend.cancel();
this.eventEmitter.removeAllListeners();
}
send() {
this.eventEmitter.emit("send");
}
};
// src/index.ts
var strategy = {
InstantStrategy,
OnBundleSizeStrategy,
OnRequestStrategy,
OnIntervalStrategy,
HybridStrategy
};
var service = {
BaseRemoteService,
SumologicService,
LogglyService,
ConsoleService,
ElasticsearchService
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
AdvancedLogger,
TransformationEnum,
service,
strategy
});
//# sourceMappingURL=index.cjs.map