plogger-sdk
Version:
Typescript based frontend logging library compatible with multiple transports and JS/TS frameworks
824 lines (780 loc) • 33.8 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("pLoggerSDK", [], factory);
else if(typeof exports === 'object')
exports["pLoggerSDK"] = factory();
else
root["pLoggerSDK"] = factory();
})(self, () => {
return /******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ "./src/Logger.ts":
/*!***********************!*\
!*** ./src/Logger.ts ***!
\***********************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BaseLogger = void 0;
var logLevel_1 = __webpack_require__(/*! ./logLevel */ "./src/logLevel.ts");
var BaseLogger = /** @class */ (function () {
function BaseLogger() {
/**
* defines the enum keys for standardized messaging.
*/
this.logEnums = {};
this.formatter = "[{{levelName}}] {{timestampLocalIso}} {{scope}} : {{rawMessage}}";
this.level = logLevel_1.logLevel.Debug;
}
/**
* sets the threshold level on which any log called with a higher rank / lower priority will be ignored.
* @param log_level logLevel
*/
BaseLogger.prototype.setLevel = function (log_level) {
this.level = log_level;
}; //change this argument type to logLevelstrings
BaseLogger.prototype.getLevel = function () {
return this.level;
};
/**
* sets a formatter to the log message for the browser
* @param formatter string
*/
BaseLogger.prototype.setFormatter = function (formatter) {
this.formatter = formatter;
};
/**
* Generates the formatted log message.
* @param log - logRecord
* @returns
*/
BaseLogger.prototype.formatLog = function (log) {
var placeholderValues = log.getFormatPlaceholders();
var current_formatter = log.formatter != null ? log.formatter : this.formatter;
return current_formatter.replace(/{{(.+?)}}/g, function (_, placeholder) {
return placeholderValues[placeholder] != null
? placeholderValues[placeholder]
: "";
});
};
return BaseLogger;
}());
exports.BaseLogger = BaseLogger;
/***/ }),
/***/ "./src/console/console-logger.ts":
/*!***************************************!*\
!*** ./src/console/console-logger.ts ***!
\***************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ConsoleLogger = void 0;
var Logger_1 = __webpack_require__(/*! ../Logger */ "./src/Logger.ts");
var logLevel_1 = __webpack_require__(/*! ../logLevel */ "./src/logLevel.ts");
var ConsoleLogger = /** @class */ (function (_super) {
__extends(ConsoleLogger, _super);
function ConsoleLogger() {
var _this = _super.call(this) || this;
//base formatter
_this.formatter = "[{{levelName}}] {{timestampLocalIso}} {{filePathWithLine}} {{scope}} : {{rawMessage}}";
return _this;
}
ConsoleLogger.prototype.log = function (logRecord) {
var formattedLog = this.formatLog(logRecord);
switch (logRecord.level) {
case logLevel_1.logLevel.Debug:
console.debug(formattedLog);
break;
case logLevel_1.logLevel.Critical:
console.error(formattedLog);
break;
case logLevel_1.logLevel.Error:
console.error(formattedLog);
break;
case logLevel_1.logLevel.Info:
console.info(formattedLog);
break;
case logLevel_1.logLevel.Warn:
console.warn(formattedLog);
break;
case logLevel_1.logLevel.Trace:
console.trace(formattedLog);
break;
default:
console.log(formattedLog);
break;
}
};
return ConsoleLogger;
}(Logger_1.BaseLogger));
exports.ConsoleLogger = ConsoleLogger;
/***/ }),
/***/ "./src/helperMethods.ts":
/*!******************************!*\
!*** ./src/helperMethods.ts ***!
\******************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.jsonStringifyRecursive = void 0;
var errorObj_1 = __webpack_require__(/*! ./logs/errorObj */ "./src/logs/errorObj.ts");
function jsonStringifyRecursive(obj) {
var cache = new Set();
return JSON.stringify(obj, function (_, value) {
if (typeof value === "object" && value !== null) {
if (cache.has(value)) {
// Circular reference found, discard key
// return "[Circular]";
}
// Store value in our collection
cache.add(value);
}
if ((0, errorObj_1.isError)(value)) {
return (0, errorObj_1.stringifyErrorObject)(value);
}
return value;
});
}
exports.jsonStringifyRecursive = jsonStringifyRecursive;
/***/ }),
/***/ "./src/http/http-logger.ts":
/*!*********************************!*\
!*** ./src/http/http-logger.ts ***!
\*********************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.HttpLogger = void 0;
var Logger_1 = __webpack_require__(/*! ../Logger */ "./src/Logger.ts");
var helperMethods_1 = __webpack_require__(/*! ../helperMethods */ "./src/helperMethods.ts");
var logLevel_1 = __webpack_require__(/*! ../logLevel */ "./src/logLevel.ts");
/**
* HttpLogger -> defines the logger to infer logs to the remote server
*/
var HttpLogger = /** @class */ (function (_super) {
__extends(HttpLogger, _super);
function HttpLogger(_a) {
var _b = _a.serverUrl, serverUrl = _b === void 0 ? "api/url" : _b, _c = _a.batchOptions, batchOptions = _c === void 0 ? null : _c, _d = _a.retryOptions, retryOptions = _d === void 0 ? { maxRetries: 3, retryDelay: 1000 } : _d, _e = _a.highPriority, highPriority = _e === void 0 ? logLevel_1.logLevel.Critical : _e, _f = _a.setCredentials, setCredentials = _f === void 0 ? false : _f, _g = _a.showFormattedLog, showFormattedLog = _g === void 0 ? false : _g;
var _this = _super.call(this) || this;
/**define the timeout object to flush the last log batch*/
_this.timeoutRef = null;
_this.logBucket = [];
// this.config = config;
_this.serverUrl = serverUrl;
_this.batchOptions = batchOptions;
_this.retryOptions = retryOptions;
_this.highPriority = highPriority;
_this.setCredentials = setCredentials;
_this.showFormattedLog = showFormattedLog;
//out of the config
_this.headers = {}; //default headers
return _this;
}
HttpLogger.prototype._buildLogObject = function (log) {
return {
level: logLevel_1.logLevels[log.level],
timestamp: log.timestamp.toISOString(),
log: log.log,
scope: log.scope,
metaData: log.metaData,
};
};
HttpLogger.prototype.setPriorityLog = function (priority_level) {
this.highPriority = priority_level;
};
/**
* Set custom headers to your Http Request
* @param headers Headers()
*/
HttpLogger.prototype.setHeaders = function (headers) {
this.headers = headers;
};
HttpLogger.prototype.log = function (logRecord) {
var _this = this;
var http_log = {
logData: this._buildLogObject(logRecord),
};
if (this.showFormattedLog) {
http_log.formattedLog = this.formatLog(logRecord);
}
//if batchOptions doesn't exist
if (this.batchOptions == null) {
//batchOptions doesn't exist
this.sendBatchRequest([http_log]);
return;
}
//HighPriority threshold
if (logLevel_1.logLevels[this.highPriority].rank >= http_log.logData.level.rank) {
//push this log directly to the server instead of the batch.
this.sendBatchRequest([http_log]);
}
else {
this.logBucket.push(http_log);
}
// log batch flush upon exceeding batchSize
if (this.logBucket.length >= this.batchOptions.batchSize) {
this.sendBatchRequest();
}
if (this.timeoutRef != null) {
return;
}
// log batch flush upon not fulfilling batchSize
this.timeoutRef = setTimeout(function () {
clearTimeout(_this.timeoutRef);
_this.timeoutRef = null;
if (_this.logBucket.length > 0) {
_this.sendBatchRequest();
}
}, this.batchOptions.debounceTime);
};
HttpLogger.prototype.sendBatchRequest = function (batchPayload) {
if (batchPayload === void 0) { batchPayload = null; }
var _tempBuffer = batchPayload;
if (batchPayload == null) {
_tempBuffer = this.logBucket;
this.logBucket = [];
}
// this.logBucket = [];
var _emitBatch = { logBuffer: _tempBuffer };
this.sendRequest(this.serverUrl, _emitBatch, this.retryOptions.maxRetries, this.retryOptions.retryDelay, this.setCredentials, this.headers);
};
HttpLogger.prototype.sendRequest = function (serverUrl, requestData, maxRetries, backoffTimeout, setCredentials, headers) {
var _this = this;
// "Accept": "application/json",
var retryCodes = [408, 500, 502, 503, 504, 522, 404, 400, 405];
var fetchHeaders = new Headers({
"Content-Type": "application/json",
});
var credentialHeader = setCredentials
? "include"
: "omit";
for (var _i = 0, _a = Object.entries(headers); _i < _a.length; _i++) {
var _b = _a[_i], key = _b[0], value = _b[1];
fetchHeaders.append(key, value);
}
fetch(serverUrl, {
method: "POST",
credentials: credentialHeader,
headers: fetchHeaders,
body: (0, helperMethods_1.jsonStringifyRecursive)(requestData),
}).then(function (response) {
// return response.json();
if (response.ok) {
return response.json();
}
if (maxRetries > 0 && retryCodes.includes(response.status)) {
setTimeout(function () {
return _this.sendRequest(serverUrl, requestData, maxRetries - 1, backoffTimeout * 2, setCredentials, headers);
}, backoffTimeout);
}
else {
throw new Error("Response error occured...".concat(response));
}
});
};
return HttpLogger;
}(Logger_1.BaseLogger));
exports.HttpLogger = HttpLogger;
/***/ }),
/***/ "./src/logLevel.ts":
/*!*************************!*\
!*** ./src/logLevel.ts ***!
\*************************/
/***/ ((__unused_webpack_module, exports) => {
var _a;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.logLevels = exports.logLevel = void 0;
var logLevel;
(function (logLevel) {
logLevel["Critical"] = "Critical";
logLevel["Error"] = "Error";
logLevel["Warn"] = "Warn";
logLevel["Info"] = "Info";
logLevel["Trace"] = "Trace";
logLevel["Debug"] = "Debug";
})(logLevel || (exports.logLevel = logLevel = {}));
exports.logLevels = (_a = {},
_a[logLevel.Critical] = { rank: 0, name: "CRITICAL" },
_a[logLevel.Error] = { rank: 1, name: "ERROR" },
_a[logLevel.Warn] = { rank: 2, name: "WARN" },
_a[logLevel.Info] = { rank: 3, name: "INFO" },
_a[logLevel.Trace] = { rank: 4, name: "TRACE" },
_a[logLevel.Debug] = { rank: 5, name: "DEBUG" },
_a);
/***/ }),
/***/ "./src/logs/errorObj.ts":
/*!******************************!*\
!*** ./src/logs/errorObj.ts ***!
\******************************/
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getCallerStackFrame = exports.toErrorObject = exports.stringifyErrorObject = exports.isError = void 0;
function isError(e) {
return e instanceof Error;
}
exports.isError = isError;
function stringifyErrorObject(e) {
var newValue = Object.getOwnPropertyNames(e).reduce(function (obj, propName) {
obj[propName] = e[propName];
return obj;
}, { name: e.name });
return newValue;
}
exports.stringifyErrorObject = stringifyErrorObject;
function toErrorObject(error) {
var _a;
return {
nativeError: error,
name: (_a = error.name) !== null && _a !== void 0 ? _a : "Error",
message: error.message,
stack: _getErrorTrace(error),
};
}
exports.toErrorObject = toErrorObject;
function _getErrorTrace(error) {
var _a, _b, _c;
return (_c = (_b = (_a = error === null || error === void 0 ? void 0 : error.stack) === null || _a === void 0 ? void 0 : _a.split("\n")) === null || _b === void 0 ? void 0 : _b.filter(function (line) { return !line.includes("Error: "); })) === null || _c === void 0 ? void 0 : _c.reduce(function (result, line) {
var stackData = stackLineToStackFrame(line);
if (!Object.values(stackData).every(function (el) { return el === undefined; })) {
result.push(stackData);
}
return result;
}, []);
}
function stackLineToStackFrame(line) {
var pathRegexes = [
/^\s?((?:at)\s)?(?:(?<method>[\w.]*)(?:\s|@))?\(?(?:file|https|http|webpack|[^@]+)?(?:file:)?:\/?\/?\w*:?\d*\/(?<fileName>[\w./-]+)\??(?::(?<lineNumber>\d+))?(?::(?<colNumber>\d+))?/,
/(?:(?:file|https?|global code|[^@]+)@)?(?:file:)?(?<fileName>(?:\/[^:/]+){2,})(?::(?<lineNumber>\d+))?(?::(?<colNumber>\d+))?/,
];
var href = globalThis.location.origin;
var pathResult = {
fullFilePath: undefined,
fileName: undefined,
fileNameWithLine: undefined,
fileColumn: undefined,
fileLine: undefined,
filePath: undefined,
filePathWithLine: undefined,
method: undefined,
};
if (line != null) {
for (var i = 0; i < pathRegexes.length; i++) {
var pathRegex = pathRegexes[i];
var match = line.trim().match(pathRegex);
if (match) {
var match_group = match["groups"];
pathResult.filePath = match_group["fileName"].replace(/\?.*$/, "");
pathResult.fullFilePath = "".concat(href).concat(pathResult.filePath);
var pathParts = pathResult.filePath.split("/");
pathResult.fileName = pathParts[pathParts.length - 1];
pathResult.fileLine = match_group["lineNumber"];
pathResult.fileColumn = match_group["colNumber"];
pathResult.method = match_group["method"];
pathResult.filePathWithLine = "".concat(pathResult.filePath, ":").concat(pathResult.fileLine);
pathResult.fileNameWithLine = "".concat(pathResult.fileName, ":").concat(pathResult.fileLine);
break;
}
}
}
return pathResult;
}
function getCallerStackFrame(stackDepthLevel, error) {
var _a, _b, _c;
if (error === void 0) { error = Error(); }
var userAgentString = (navigator === null || navigator === void 0 ? void 0 : navigator.userAgent) || "";
var _stackDepthLevel = userAgentString.match(/.*Firefox.*/)
? stackDepthLevel - 1
: stackDepthLevel;
return stackLineToStackFrame((_c = (_b = (_a = error === null || error === void 0 ? void 0 : error.stack) === null || _a === void 0 ? void 0 : _a.split("\n")) === null || _b === void 0 ? void 0 : _b.filter(function (line) {
return !line.includes("Error: ");
})) === null || _c === void 0 ? void 0 : _c[_stackDepthLevel]);
}
exports.getCallerStackFrame = getCallerStackFrame;
/***/ }),
/***/ "./src/logs/log-record.ts":
/*!********************************!*\
!*** ./src/logs/log-record.ts ***!
\********************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.logRecord = void 0;
var logLevel_1 = __webpack_require__(/*! ../logLevel */ "./src/logLevel.ts");
// import {LogHelper} from './log-helper'
var helperMethods_1 = __webpack_require__(/*! ../helperMethods */ "./src/helperMethods.ts");
var errorObj_1 = __webpack_require__(/*! ./errorObj */ "./src/logs/errorObj.ts");
var logRecord = /** @class */ (function () {
function logRecord(level, scope, message, formatter, staticParams, enumMessage, timestampGenerator) {
this.metaData = null;
this.level = level;
this.scope = scope;
if (this.timestampGenerator) {
this.timestamp = this.timestampGenerator();
}
else {
this.timestamp = new Date();
}
var current_enumMessage = enumMessage;
// checking if message is an error object
var current_message = null;
if ((0, errorObj_1.isError)(message)) {
var error_obj = (0, errorObj_1.toErrorObject)(message);
var _1 = error_obj.stack, temp_curr_message = __rest(error_obj, ["stack"]);
this.metaData = error_obj.stack;
current_message = temp_curr_message;
}
else {
current_message = {
message: message,
};
}
this.log = __assign(__assign(__assign({}, current_message), { staticParams: staticParams }), current_enumMessage);
this.rawMessage = message;
this.formatter = formatter;
}
logRecord.prototype.fetchCallStack = function (stackDepth) {
this.metaData = (0, errorObj_1.getCallerStackFrame)(stackDepth);
};
logRecord.prototype.generateFormatPlaceholders = function () {
var _a, _b, _c, _d;
this.formatPlaceholders = {};
//denotes log level name
this.formatPlaceholders["levelName"] = logLevel_1.logLevels[this.level].name;
//denotes the log level rank
this.formatPlaceholders["levelRank"] = logLevel_1.logLevels[this.level].rank;
//denotes the timestamp in POSIX format
this.formatPlaceholders["timestampEpoch"] = this.timestamp;
//denotes the timestamp in ISO format
this.formatPlaceholders["timestampISO"] = this.timestamp.toISOString();
//the scope of the logger, also defined as "name" in pLogger constructor
this.formatPlaceholders["scope"] = this.scope;
//the message entered by the user, could be a raw string or a enum message mapped to the string/key (check setLogEnums() and setEnumMessages())
this.formatPlaceholders["message"] = (0, helperMethods_1.jsonStringifyRecursive)(this.log);
//the string message entered by the user
this.formatPlaceholders["rawMessage"] = (0, helperMethods_1.jsonStringifyRecursive)(this.rawMessage);
//Return the time value of the system
this.formatPlaceholders["timestampLocalIso"] = new Date(this.timestamp.getTime() - this.timestamp.getTimezoneOffset() * 60000).toISOString();
var metaData = null;
if (Array.isArray(this.metaData)) {
metaData = this.metaData[0];
}
else {
metaData = this.metaData;
}
//Returns the filename where the log is present along with the line number
this.formatPlaceholders["fileNameWithLine"] =
(_a = metaData === null || metaData === void 0 ? void 0 : metaData.fileNameWithLine) !== null && _a !== void 0 ? _a : "";
//Return the filepath where the log is present along with the line number
this.formatPlaceholders["filePathWithLine"] =
(_b = metaData === null || metaData === void 0 ? void 0 : metaData.filePathWithLine) !== null && _b !== void 0 ? _b : "";
//Return the full file path
this.formatPlaceholders["fullFilePath"] = (_c = metaData === null || metaData === void 0 ? void 0 : metaData.fullFilePath) !== null && _c !== void 0 ? _c : "";
//Return the method in which the log is being called.
this.formatPlaceholders["method"] = (_d = metaData === null || metaData === void 0 ? void 0 : metaData.method) !== null && _d !== void 0 ? _d : "";
};
logRecord.prototype.getFormatPlaceholders = function () {
if (this.formatPlaceholders === undefined) {
this.generateFormatPlaceholders();
}
return this.formatPlaceholders;
};
return logRecord;
}());
exports.logRecord = logRecord;
/***/ }),
/***/ "./src/p-logger/p-logger.ts":
/*!**********************************!*\
!*** ./src/p-logger/p-logger.ts ***!
\**********************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.logLevel = exports.pLogger = void 0;
var Logger_1 = __webpack_require__(/*! ../Logger */ "./src/Logger.ts");
var logLevel_1 = __webpack_require__(/*! ../logLevel */ "./src/logLevel.ts");
Object.defineProperty(exports, "logLevel", ({ enumerable: true, get: function () { return logLevel_1.logLevel; } }));
var log_record_1 = __webpack_require__(/*! ../logs/log-record */ "./src/logs/log-record.ts");
/**
* The main library abstraction
* @param name string
* @param hideLogPositionForPerformance boolean
* @param stackDepth number
* @param minLevel logLevel
* @param formatter string
* @param staticParams Object
*/
var pLogger = /** @class */ (function (_super) {
__extends(pLogger, _super);
function pLogger(_a) {
var _b = _a.name, name = _b === void 0 ? "Root" : _b, _c = _a.minLevel, minLevel = _c === void 0 ? null : _c, _d = _a.formatter, formatter = _d === void 0 ? null : _d, _e = _a.staticParams, staticParams = _e === void 0 ? {} : _e, _f = _a.hideLogPositionForPerformance, hideLogPositionForPerformance = _f === void 0 ? true : _f, _g = _a.stackDepth, stackDepth = _g === void 0 ? 0 : _g;
var _this = _super.call(this) || this;
_this.handlers = [];
_this.level = minLevel;
_this.formatter = formatter;
_this.name = name;
_this.hideLogPositionForPerformance = hideLogPositionForPerformance;
_this.stackDepth = stackDepth;
_this.staticParams = staticParams;
_this.logEnums = {};
_this.enumMessages = {};
_this.timestampGenerator = null;
return _this;
}
/**
* Add the logger to send the logs to respective transports.
* @param logger BaseLogger
*/
pLogger.prototype.addHandler = function (logger) {
var index = this.handlers.indexOf(logger, 0);
if (index == -1) {
this.handlers.push(logger);
}
};
pLogger.prototype.removeHandler = function (logger) {
var index = this.handlers.indexOf(logger, 0);
if (index > -1) {
this.handlers.splice(index, 1);
}
};
pLogger.prototype.checkHandlers = function () {
//using this method for debugging purposes
console.trace("pLoggerSDK Handlers: ", this.handlers);
};
pLogger.prototype.setTimestampGenerator = function (timestampGenerator) {
this.timestampGenerator = timestampGenerator;
};
// setLevel log threshold
pLogger.prototype.verify_log_level = function (threshold, incoming_level) {
if (threshold != null &&
logLevel_1.logLevels[incoming_level].rank > logLevel_1.logLevels[threshold].rank) {
return false;
}
return true;
};
/**
*
* @param logEnums - user defined object keys
* defined in format
* {
* key1 : "key1",
* key2 : "key2"
* ...
* }
*/
pLogger.prototype.setLogEnums = function (logEnums) {
this.logEnums = logEnums;
};
/**
*
* @param enumMessages - user defined object consisting of message object literals mapped to logEnums
*/
pLogger.prototype.setEnumMessages = function (enumMessages) {
this.enumMessages = enumMessages;
};
/**
* define new staticParams for pLogger
* @param newParams - dynamic object literal
*/
pLogger.prototype.updateParams = function (newParams) {
this.staticParams = newParams;
};
/**
* add on new staticParams or override preexisting staticParams.
* @param newParams - dynamic object literal
*/
pLogger.prototype.appendParams = function (newParams) {
var buffer = __assign(__assign({}, this.staticParams), newParams);
this.staticParams = buffer;
};
pLogger.prototype.log = function (logRecord) {
return;
};
pLogger.prototype._log = function (message, log_level, staticParams) {
var _this = this;
if (staticParams === void 0) { staticParams = null; }
//taking log based enum if the string message is in the enum keys.
var logData = this.enumMessages[message];
var enum_message;
if (logData) {
enum_message = __assign({}, logData);
}
else {
enum_message = null;
}
var currentParams;
if (staticParams != null) {
currentParams = __assign(__assign({}, this.staticParams), staticParams);
}
else {
currentParams = this.staticParams;
}
var current_log = new log_record_1.logRecord(log_level, this.name, message, this.formatter, currentParams, enum_message, this.timestampGenerator);
if ((!this.hideLogPositionForPerformance && this.stackDepth > 0) ||
logLevel_1.logLevels[log_level].rank <= logLevel_1.logLevels[logLevel_1.logLevel.Error].rank) {
current_log.fetchCallStack(this.stackDepth);
}
if (!this.verify_log_level(this.level, log_level)) {
return;
}
//sending log to each handler.
this.handlers.forEach(function (handler) {
if (!_this.verify_log_level(handler.getLevel(), log_level)) {
return;
}
handler.log(current_log);
});
};
pLogger.prototype.critical = function (message, staticParams) {
if (staticParams === void 0) { staticParams = null; }
this._log(message, logLevel_1.logLevel.Critical, staticParams);
};
pLogger.prototype.error = function (message, staticParams) {
if (staticParams === void 0) { staticParams = null; }
this._log(message, logLevel_1.logLevel.Error, staticParams);
};
pLogger.prototype.info = function (message, staticParams) {
if (staticParams === void 0) { staticParams = null; }
this._log(message, logLevel_1.logLevel.Info, staticParams);
};
pLogger.prototype.debug = function (message, staticParams) {
if (staticParams === void 0) { staticParams = null; }
this._log(message, logLevel_1.logLevel.Debug, staticParams);
};
pLogger.prototype.warn = function (message, staticParams) {
if (staticParams === void 0) { staticParams = null; }
this._log(message, logLevel_1.logLevel.Warn, staticParams);
};
pLogger.prototype.trace = function (message, staticParams) {
if (staticParams === void 0) { staticParams = null; }
this._log(message, logLevel_1.logLevel.Trace, staticParams);
};
return pLogger;
}(Logger_1.BaseLogger));
exports.pLogger = pLogger;
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {
var exports = __webpack_exports__;
/*!**********************!*\
!*** ./src/index.ts ***!
\**********************/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.pLogger = exports.logLevel = exports.HttpLogger = exports.ConsoleLogger = void 0;
//public-api
var console_logger_1 = __webpack_require__(/*! ./console/console-logger */ "./src/console/console-logger.ts");
Object.defineProperty(exports, "ConsoleLogger", ({ enumerable: true, get: function () { return console_logger_1.ConsoleLogger; } }));
var http_logger_1 = __webpack_require__(/*! ./http/http-logger */ "./src/http/http-logger.ts");
Object.defineProperty(exports, "HttpLogger", ({ enumerable: true, get: function () { return http_logger_1.HttpLogger; } }));
var logLevel_1 = __webpack_require__(/*! ./logLevel */ "./src/logLevel.ts");
Object.defineProperty(exports, "logLevel", ({ enumerable: true, get: function () { return logLevel_1.logLevel; } }));
var p_logger_1 = __webpack_require__(/*! ./p-logger/p-logger */ "./src/p-logger/p-logger.ts");
Object.defineProperty(exports, "pLogger", ({ enumerable: true, get: function () { return p_logger_1.pLogger; } }));
})();
/******/ return __webpack_exports__;
/******/ })()
;
});
//# sourceMappingURL=plogger.js.map