UNPKG

ngx-logger

Version:

[![npm version](https://badge.fury.io/js/ngx-logger.svg)](https://www.npmjs.com/package/ngx-logger)

1,005 lines (984 loc) 67.2 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/common/http'), require('@angular/core'), require('rxjs'), require('rxjs/operators'), require('vlq'), require('@angular/common')) : typeof define === 'function' && define.amd ? define('ngx-logger', ['exports', '@angular/common/http', '@angular/core', 'rxjs', 'rxjs/operators', 'vlq', '@angular/common'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['ngx-logger'] = {}, global.ng.common.http, global.ng.core, global.rxjs, global.rxjs.operators, global.vlq, global.ng.common)); }(this, (function (exports, i1, i0, rxjs, operators, vlq, i1$1) { 'use strict'; /** * Injection token of logger config */ var TOKEN_LOGGER_CONFIG = 'TOKEN_LOGGER_CONFIG'; var NGXLoggerConfigEngine = /** @class */ (function () { function NGXLoggerConfigEngine(config) { this.config = this._clone(config); } Object.defineProperty(NGXLoggerConfigEngine.prototype, "level", { /** Get a readonly access to the level configured for the NGXLogger */ get: function () { return this.config.level; }, enumerable: false, configurable: true }); Object.defineProperty(NGXLoggerConfigEngine.prototype, "serverLogLevel", { /** Get a readonly access to the serverLogLevel configured for the NGXLogger */ get: function () { return this.config.serverLogLevel; }, enumerable: false, configurable: true }); NGXLoggerConfigEngine.prototype.updateConfig = function (config) { this.config = this._clone(config); }; NGXLoggerConfigEngine.prototype.getConfig = function () { return this._clone(this.config); }; // TODO: This is a shallow clone, If the config ever becomes hierarchical we must make this a deep clone NGXLoggerConfigEngine.prototype._clone = function (object) { var cloneConfig = { level: null }; Object.keys(object).forEach(function (key) { cloneConfig[key] = object[key]; }); return cloneConfig; }; return NGXLoggerConfigEngine; }()); /** * Injection token of logger config engine factory */ var TOKEN_LOGGER_CONFIG_ENGINE_FACTORY = 'TOKEN_LOGGER_CONFIG_ENGINE_FACTORY'; var NGXLoggerConfigEngineFactory = /** @class */ (function () { function NGXLoggerConfigEngineFactory() { } NGXLoggerConfigEngineFactory.prototype.provideConfigEngine = function (config) { return new NGXLoggerConfigEngine(config); }; return NGXLoggerConfigEngineFactory; }()); /** * Injection token of logger mapper service */ var TOKEN_LOGGER_MAPPER_SERVICE = 'TOKEN_LOGGER_MAPPER_SERVICE'; var NGXLoggerMapperService = /** @class */ (function () { function NGXLoggerMapperService(httpBackend) { this.httpBackend = httpBackend; /** cache for source maps, key is source map location, ie. 'http://localhost:4200/main.js.map' */ this.sourceMapCache = new Map(); /** cache for specific log position, key is the dist position, ie 'main.js:339:21' */ this.logPositionCache = new Map(); } /** * Returns the log position of the caller * If sourceMaps are enabled, it attemps to get the source map from the server, and use that to parse the position * @param config * @param metadata * @returns */ NGXLoggerMapperService.prototype.getLogPosition = function (config, metadata) { var stackLine = this.getStackLine(config); // if we were not able to parse the stackLine, just return an empty Log Position if (!stackLine) { return rxjs.of({ fileName: '', lineNumber: 0, columnNumber: 0 }); } var logPosition = this.getLocalPosition(stackLine); if (!config.enableSourceMaps) { return rxjs.of(logPosition); } var sourceMapLocation = this.getSourceMapLocation(stackLine); return this.getSourceMap(sourceMapLocation, logPosition); }; /** * Get the stackline of the original caller * @param config * @returns null if stackline was not found */ NGXLoggerMapperService.prototype.getStackLine = function (config) { var error = new Error(); try { // noinspection ExceptionCaughtLocallyJS throw error; } catch (e) { try { // Here are different examples of stacktrace // Firefox (last line is the user code, the 4 first are ours): // getStackLine@http://localhost:4200/main.js:358:23 // getCallerDetails@http://localhost:4200/main.js:557:44 // _log@http://localhost:4200/main.js:830:28 // debug@http://localhost:4200/main.js:652:14 // handleLog@http://localhost:4200/main.js:1158:29 // Chrome and Edge (last line is the user code): // Error // at Function.getStackLine (ngx-logger.js:329) // at NGXMapperService.getCallerDetails (ngx-logger.js:528) // at NGXLogger._log (ngx-logger.js:801) // at NGXLogger.info (ngx-logger.js:631) // at AppComponent.handleLog (app.component.ts:38) var defaultProxy = 4; // We make 4 functions call before getting here var firstStackLine = error.stack.split('\n')[0]; if (!firstStackLine.includes('.js:')) { // The stacktrace starts with no function call (example in Chrome or Edge) defaultProxy = defaultProxy + 1; } return error.stack.split('\n')[(defaultProxy + (config.proxiedSteps || 0))]; } catch (e) { return null; } } }; /** * Get position of caller without using sourceMaps * @param stackLine * @returns */ NGXLoggerMapperService.prototype.getLocalPosition = function (stackLine) { // strip base path, then parse filename, line, and column, stackline looks like this : // Firefox // handleLog@http://localhost:4200/main.js:1158:29 // Chrome and Edge // at AppComponent.handleLog (app.component.ts:38) var positionStartIndex = stackLine.lastIndexOf('\/'); var positionEndIndex = stackLine.indexOf(')'); if (positionEndIndex < 0) { positionEndIndex = undefined; } var position = stackLine.substring(positionStartIndex + 1, positionEndIndex); var dataArray = position.split(':'); if (dataArray.length === 3) { return { fileName: dataArray[0], lineNumber: +dataArray[1], columnNumber: +dataArray[2] }; } return { fileName: 'unknown', lineNumber: 0, columnNumber: 0 }; }; NGXLoggerMapperService.prototype.getTranspileLocation = function (stackLine) { // Example stackLine: // Firefox : getStackLine@http://localhost:4200/main.js:358:23 // Chrome and Edge : at Function.getStackLine (ngx-logger.js:329) var locationStartIndex = stackLine.indexOf('('); if (locationStartIndex < 0) { locationStartIndex = stackLine.lastIndexOf('@'); if (locationStartIndex < 0) { locationStartIndex = stackLine.lastIndexOf(' '); } } var locationEndIndex = stackLine.indexOf(')'); if (locationEndIndex < 0) { locationEndIndex = undefined; } return stackLine.substring(locationStartIndex + 1, locationEndIndex); }; /** * Gets the URL of the sourcemap (the URL can be relative or absolute, it is browser dependant) * @param stackLine * @returns */ NGXLoggerMapperService.prototype.getSourceMapLocation = function (stackLine) { var file = this.getTranspileLocation(stackLine); var mapFullPath = file.substring(0, file.lastIndexOf(':')); return mapFullPath.substring(0, mapFullPath.lastIndexOf(':')) + '.map'; }; NGXLoggerMapperService.prototype.getMapping = function (sourceMap, position) { // => ';' indicates end of a line // => ',' separates mappings in a line // decoded mapping => [ generatedCodeColumn, sourceFileIndex, sourceCodeLine, sourceCodeColumn, nameIndex ] var sourceFileIndex = 0, // second field sourceCodeLine = 0, // third field sourceCodeColumn = 0; // fourth field var lines = sourceMap.mappings.split(';'); for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) { // reset column position to 0 after each line var generatedCodeColumn = 0; // decode sections in line var columns = lines[lineIndex].split(','); for (var columnIndex = 0; columnIndex < columns.length; columnIndex++) { var decodedSection = vlq.decode(columns[columnIndex]); if (decodedSection.length >= 4) { // update relative positions generatedCodeColumn += decodedSection[0]; sourceFileIndex += decodedSection[1]; sourceCodeLine += decodedSection[2]; sourceCodeColumn += decodedSection[3]; } // check if matching map if (lineIndex === position.lineNumber) { if (generatedCodeColumn === position.columnNumber) { // matching column and line found return { fileName: sourceMap.sources[sourceFileIndex], lineNumber: sourceCodeLine, columnNumber: sourceCodeColumn }; } else if (columnIndex + 1 === columns.length) { // matching column not found, but line is correct return { fileName: sourceMap.sources[sourceFileIndex], lineNumber: sourceCodeLine, columnNumber: 0 }; } } } } // failed if reached return { fileName: 'unknown', lineNumber: 0, columnNumber: 0 }; }; /** * does the http get request to get the source map * @param sourceMapLocation * @param distPosition */ NGXLoggerMapperService.prototype.getSourceMap = function (sourceMapLocation, distPosition) { var _this = this; var req = new i1.HttpRequest('GET', sourceMapLocation); var distPositionKey = distPosition.fileName + ":" + distPosition.lineNumber + ":" + distPosition.columnNumber; // if the specific log position is already in cache return it if (this.logPositionCache.has(distPositionKey)) { return this.logPositionCache.get(distPositionKey); } // otherwise check if the source map is already cached for given source map location if (!this.sourceMapCache.has(sourceMapLocation)) { if (!this.httpBackend) { console.error('NGXLogger : Can\'t get sourcemap because HttpBackend is not provided. You need to import HttpClientModule'); this.sourceMapCache.set(sourceMapLocation, rxjs.of(null)); } else { // obtain the source map if not cached this.sourceMapCache.set(sourceMapLocation, this.httpBackend.handle(req).pipe(operators.filter(function (e) { return e instanceof i1.HttpResponse; }), operators.map(function (httpResponse) { return httpResponse.body; }), operators.retry(3), operators.shareReplay(1))); } } // at this point the source map is cached, use it to get specific log position mapping var logPosition$ = this.sourceMapCache.get(sourceMapLocation).pipe(operators.map(function (sourceMap) { // sourceMap can be null if HttpBackend is not provided for example if (!sourceMap) { return distPosition; } // map generated position to source position return _this.getMapping(sourceMap, distPosition); }), operators.catchError(function () { return rxjs.of(distPosition); }), operators.shareReplay(1)); // store specific log position in cache for given dest position and return it this.logPositionCache.set(distPositionKey, logPosition$); return logPosition$; }; return NGXLoggerMapperService; }()); /** @nocollapse */ NGXLoggerMapperService.ɵfac = function NGXLoggerMapperService_Factory(t) { return new (t || NGXLoggerMapperService)(i0.ɵɵinject(i1.HttpBackend, 8)); }; /** @nocollapse */ NGXLoggerMapperService.ɵprov = i0.ɵɵdefineInjectable({ token: NGXLoggerMapperService, factory: NGXLoggerMapperService.ɵfac }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(NGXLoggerMapperService, [{ type: i0.Injectable }], function () { return [{ type: i1.HttpBackend, decorators: [{ type: i0.Optional }] }]; }, null); })(); /** * Injection token of logger metadata service */ var TOKEN_LOGGER_METADATA_SERVICE = 'TOKEN_LOGGER_METADATA_SERVICE'; var NGXLoggerMetadataService = /** @class */ (function () { function NGXLoggerMetadataService(datePipe) { this.datePipe = datePipe; } NGXLoggerMetadataService.prototype.computeTimestamp = function (config) { var defaultTimestamp = function () { return new Date().toISOString(); }; if (config.timestampFormat) { if (!this.datePipe) { console.error('NGXLogger : Can\'t use timeStampFormat because DatePipe is not provided. You need to provide DatePipe'); return defaultTimestamp(); } else { return this.datePipe.transform(new Date(), config.timestampFormat); } } return defaultTimestamp(); }; NGXLoggerMetadataService.prototype.getMetadata = function (level, config, message, additional) { var metadata = { level: level, additional: additional, }; // The user can send a function // This is useful in order to compute string concatenation only when the log will actually be written if (message && typeof message === 'function') { metadata.message = message(); } else { metadata.message = message; } metadata.timestamp = this.computeTimestamp(config); return metadata; }; return NGXLoggerMetadataService; }()); /** @nocollapse */ NGXLoggerMetadataService.ɵfac = function NGXLoggerMetadataService_Factory(t) { return new (t || NGXLoggerMetadataService)(i0.ɵɵinject(i1$1.DatePipe, 8)); }; /** @nocollapse */ NGXLoggerMetadataService.ɵprov = i0.ɵɵdefineInjectable({ token: NGXLoggerMetadataService, factory: NGXLoggerMetadataService.ɵfac }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(NGXLoggerMetadataService, [{ type: i0.Injectable }], function () { return [{ type: i1$1.DatePipe, decorators: [{ type: i0.Optional }] }]; }, null); })(); // I kept this class alive only to avoid a breaking change with the old version // This class does not implement anything so it is useless and the interface is enough /** * @deprecated this class does not implement anything thus being useless, you should rather implements @see INGXLoggerMonitor */ var NGXLoggerMonitor = /** @class */ (function () { function NGXLoggerMonitor() { } return NGXLoggerMonitor; }()); /** * Injection token of logger metadata service */ var TOKEN_LOGGER_RULES_SERVICE = 'TOKEN_LOGGER_RULES_SERVICE'; var NGXLoggerRulesService = /** @class */ (function () { function NGXLoggerRulesService() { } NGXLoggerRulesService.prototype.shouldCallWriter = function (level, config, message, additional) { return !config.disableConsoleLogging && level >= config.level; }; NGXLoggerRulesService.prototype.shouldCallServer = function (level, config, message, additional) { return !!config.serverLoggingUrl && level >= config.serverLogLevel; }; NGXLoggerRulesService.prototype.shouldCallMonitor = function (level, config, message, additional) { // The default behavior is to call the monitor only if the writer or the server is called return this.shouldCallWriter(level, config, message, additional) || this.shouldCallServer(level, config, message, additional); }; return NGXLoggerRulesService; }()); /** @nocollapse */ NGXLoggerRulesService.ɵfac = function NGXLoggerRulesService_Factory(t) { return new (t || NGXLoggerRulesService)(); }; /** @nocollapse */ NGXLoggerRulesService.ɵprov = i0.ɵɵdefineInjectable({ token: NGXLoggerRulesService, factory: NGXLoggerRulesService.ɵfac }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(NGXLoggerRulesService, [{ type: i0.Injectable }], null, null); })(); /** * Injection token of logger server service */ var TOKEN_LOGGER_SERVER_SERVICE = 'TOKEN_LOGGER_SERVER_SERVICE'; var NGXLoggerServerService = /** @class */ (function () { function NGXLoggerServerService(httpBackend) { this.httpBackend = httpBackend; } /** * Transforms an error object into a readable string (taking only the stack) * This is needed because JSON.stringify would return "{}" * @param err the error object * @returns The stack of the error */ NGXLoggerServerService.prototype.secureErrorObject = function (err) { return err === null || err === void 0 ? void 0 : err.stack; }; /** * Transforms the additional parameters to avoid any json error when sending the data to the server * Basically it just replaces unstringifiable object to a string mentioning an error * @param additional The additional data to be sent * @returns The additional data secured */ NGXLoggerServerService.prototype.secureAdditionalParameters = function (additional) { var _this = this; if (additional === null || additional === undefined) { return null; } return additional.map(function (next, idx) { try { if (next instanceof Error) { return _this.secureErrorObject(next); } // We just want to make sure the JSON can be parsed, we do not want to actually change the type if (typeof next === 'object') { JSON.stringify(next); } return next; } catch (e) { return "The additional[" + idx + "] value could not be parsed using JSON.stringify()."; } }); }; /** * Transforms the message so that it can be sent to the server * @param message the message to be sent * @returns the message secured */ NGXLoggerServerService.prototype.secureMessage = function (message) { try { if (message instanceof Error) { return this.secureErrorObject(message); } if (typeof message !== 'string') { message = JSON.stringify(message, null, 2); } } catch (e) { message = 'The provided "message" value could not be parsed with JSON.stringify().'; } return message; }; NGXLoggerServerService.prototype.logOnServer = function (url, logContent, options) { // HttpBackend skips all HttpInterceptors // They may log errors using this service causing circular calls var req = new i1.HttpRequest('POST', url, logContent, options || {}); if (!this.httpBackend) { console.error('NGXLogger : Can\'t log on server because HttpBackend is not provided. You need to import HttpClientModule'); return rxjs.of(null); } return this.httpBackend.handle(req).pipe(operators.filter(function (e) { return e instanceof i1.HttpResponse; }), operators.map(function (httpResponse) { return httpResponse.body; })); }; /** * Customise the data sent to the API * @param metadata the data provided by NGXLogger * @returns the data that will be sent to the API in the body */ NGXLoggerServerService.prototype.customiseRequestBody = function (metadata) { // In our API the body is not customised return metadata; }; NGXLoggerServerService.prototype.sendToServer = function (metadata, config) { // Copying metadata locally because we don't want to change the object for the caller var localMetadata = Object.assign({}, metadata); localMetadata.additional = this.secureAdditionalParameters(localMetadata.additional); localMetadata.message = this.secureMessage(localMetadata.message); // Allow users to customise the data sent to the API var requestBody = this.customiseRequestBody(localMetadata); var headers = config.customHttpHeaders || new i1.HttpHeaders(); if (!headers.has('Content-Type')) { headers.set('Content-Type', 'application/json'); } this.logOnServer(config.serverLoggingUrl, requestBody, { headers: headers, params: config.customHttpParams || new i1.HttpParams(), responseType: config.httpResponseType || 'json', withCredentials: config.withCredentials || false, }).pipe(operators.catchError(function (err) { // Do not use NGXLogger here because this could cause an infinite loop console.error('NGXLogger: Failed to log on server', err); return rxjs.throwError(err); })).subscribe(); }; return NGXLoggerServerService; }()); /** @nocollapse */ NGXLoggerServerService.ɵfac = function NGXLoggerServerService_Factory(t) { return new (t || NGXLoggerServerService)(i0.ɵɵinject(i1.HttpBackend, 8)); }; /** @nocollapse */ NGXLoggerServerService.ɵprov = i0.ɵɵdefineInjectable({ token: NGXLoggerServerService, factory: NGXLoggerServerService.ɵfac }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(NGXLoggerServerService, [{ type: i0.Injectable }], function () { return [{ type: i1.HttpBackend, decorators: [{ type: i0.Optional }] }]; }, null); })(); /** * Injection token of logger writer service */ var TOKEN_LOGGER_WRITER_SERVICE = 'TOKEN_LOGGER_WRITER_SERVICE'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ 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); }; function __extends(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 = function () { __assign = Object.assign || function __assign(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); }; function __rest(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; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function () { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function (o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } }); }) : (function (o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } ; var __setModuleDefault = Object.create ? (function (o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function (o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } (function (NgxLoggerLevel) { NgxLoggerLevel[NgxLoggerLevel["TRACE"] = 0] = "TRACE"; NgxLoggerLevel[NgxLoggerLevel["DEBUG"] = 1] = "DEBUG"; NgxLoggerLevel[NgxLoggerLevel["INFO"] = 2] = "INFO"; NgxLoggerLevel[NgxLoggerLevel["LOG"] = 3] = "LOG"; NgxLoggerLevel[NgxLoggerLevel["WARN"] = 4] = "WARN"; NgxLoggerLevel[NgxLoggerLevel["ERROR"] = 5] = "ERROR"; NgxLoggerLevel[NgxLoggerLevel["FATAL"] = 6] = "FATAL"; NgxLoggerLevel[NgxLoggerLevel["OFF"] = 7] = "OFF"; })(exports.NgxLoggerLevel || (exports.NgxLoggerLevel = {})); var DEFAULT_COLOR_SCHEME = [ 'purple', 'teal', 'gray', 'gray', 'red', 'red', 'red' ]; var NGXLoggerWriterService = /** @class */ (function () { function NGXLoggerWriterService(platformId) { this.platformId = platformId; this.isIE = i1$1.isPlatformBrowser(platformId) && navigator && navigator.userAgent && !!(navigator.userAgent.indexOf('MSIE') !== -1 || navigator.userAgent.match(/Trident\//) || navigator.userAgent.match(/Edge\//)); this.logFunc = this.isIE ? this.logIE.bind(this) : this.logModern.bind(this); } /** Generate a "meta" string that is displayed before the content sent to the log function */ NGXLoggerWriterService.prototype.prepareMetaString = function (metadata, config) { var fileDetails = config.disableFileDetails === true ? '' : "[" + metadata.fileName + ":" + metadata.lineNumber + ":" + metadata.columnNumber + "]"; return metadata.timestamp + " " + exports.NgxLoggerLevel[metadata.level] + " " + fileDetails; }; /** Get the color to use when writing to console */ NGXLoggerWriterService.prototype.getColor = function (metadata, config) { var _a; var configColorScheme = (_a = config.colorScheme) !== null && _a !== void 0 ? _a : DEFAULT_COLOR_SCHEME; // this is needed to avoid a build error if (metadata.level === exports.NgxLoggerLevel.OFF) { return undefined; } return configColorScheme[metadata.level]; }; /** Log to the console specifically for IE */ NGXLoggerWriterService.prototype.logIE = function (metadata, config, metaString) { // Coloring doesn't work in IE // make sure additional isn't null or undefined so that ...additional doesn't error var additional = metadata.additional || []; switch (metadata.level) { case exports.NgxLoggerLevel.WARN: console.warn.apply(console, __spread([metaString + " ", metadata.message], additional)); break; case exports.NgxLoggerLevel.ERROR: case exports.NgxLoggerLevel.FATAL: console.error.apply(console, __spread([metaString + " ", metadata.message], additional)); break; case exports.NgxLoggerLevel.INFO: console.info.apply(console, __spread([metaString + " ", metadata.message], additional)); break; default: console.log.apply(console, __spread([metaString + " ", metadata.message], additional)); } }; /** Log to the console */ NGXLoggerWriterService.prototype.logModern = function (metadata, config, metaString) { var color = this.getColor(metadata, config); // make sure additional isn't null or undefined so that ...additional doesn't error var additional = metadata.additional || []; switch (metadata.level) { case exports.NgxLoggerLevel.WARN: console.warn.apply(console, __spread(["%c" + metaString, "color:" + color, metadata.message], additional)); break; case exports.NgxLoggerLevel.ERROR: case exports.NgxLoggerLevel.FATAL: console.error.apply(console, __spread(["%c" + metaString, "color:" + color, metadata.message], additional)); break; case exports.NgxLoggerLevel.INFO: console.info.apply(console, __spread(["%c" + metaString, "color:" + color, metadata.message], additional)); break; // Disabling console.trace since the stack trace is not helpful. it is showing the stack trace of // the console.trace statement // case NgxLoggerLevel.TRACE: // console.trace(`%c${metaString}`, `color:${color}`, message, ...additional); // break; case exports.NgxLoggerLevel.DEBUG: console.debug.apply(console, __spread(["%c" + metaString, "color:" + color, metadata.message], additional)); break; default: console.log.apply(console, __spread(["%c" + metaString, "color:" + color, metadata.message], additional)); } }; /** Write the content sent to the log function to the console */ NGXLoggerWriterService.prototype.writeMessage = function (metadata, config) { var metaString = this.prepareMetaString(metadata, config); this.logFunc(metadata, config, metaString); }; return NGXLoggerWriterService; }()); /** @nocollapse */ NGXLoggerWriterService.ɵfac = function NGXLoggerWriterService_Factory(t) { return new (t || NGXLoggerWriterService)(i0.ɵɵinject(i0.PLATFORM_ID)); }; /** @nocollapse */ NGXLoggerWriterService.ɵprov = i0.ɵɵdefineInjectable({ token: NGXLoggerWriterService, factory: NGXLoggerWriterService.ɵfac }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(NGXLoggerWriterService, [{ type: i0.Injectable }], function () { return [{ type: undefined, decorators: [{ type: i0.Inject, args: [i0.PLATFORM_ID] }] }]; }, null); })(); var NGXLogger = /** @class */ (function () { function NGXLogger(config, configEngineFactory, metadataService, ruleService, mapperService, writerService, serverService) { this.metadataService = metadataService; this.ruleService = ruleService; this.mapperService = mapperService; this.writerService = writerService; this.serverService = serverService; this.configEngine = configEngineFactory.provideConfigEngine(config); } Object.defineProperty(NGXLogger.prototype, "level", { /** Get a readonly access to the level configured for the NGXLogger */ get: function () { return this.configEngine.level; }, enumerable: false, configurable: true }); Object.defineProperty(NGXLogger.prototype, "serverLogLevel", { /** Get a readonly access to the serverLogLevel configured for the NGXLogger */ get: function () { return this.configEngine.serverLogLevel; }, enumerable: false, configurable: true }); NGXLogger.prototype.trace = function (message) { var additional = []; for (var _i = 1; _i < arguments.length; _i++) { additional[_i - 1] = arguments[_i]; } this._log(exports.NgxLoggerLevel.TRACE, message, additional); }; NGXLogger.prototype.debug = function (message) { var additional = []; for (var _i = 1; _i < arguments.length; _i++) { additional[_i - 1] = arguments[_i]; } this._log(exports.NgxLoggerLevel.DEBUG, message, additional); }; NGXLogger.prototype.info = function (message) { var additional = []; for (var _i = 1; _i < arguments.length; _i++) { additional[_i - 1] = arguments[_i]; } this._log(exports.NgxLoggerLevel.INFO, message, additional); }; NGXLogger.prototype.log = function (message) { var additional = []; for (var _i = 1; _i < arguments.length; _i++) { additional[_i - 1] = arguments[_i]; } this._log(exports.NgxLoggerLevel.LOG, message, additional); }; NGXLogger.prototype.warn = function (message) { var additional = []; for (var _i = 1; _i < arguments.length; _i++) { additional[_i - 1] = arguments[_i]; } this._log(exports.NgxLoggerLevel.WARN, message, additional); }; NGXLogger.prototype.error = function (message) { var additional = []; for (var _i = 1; _i < arguments.length; _i++) { additional[_i - 1] = arguments[_i]; } this._log(exports.NgxLoggerLevel.ERROR, message, additional); }; NGXLogger.prototype.fatal = function (message) { var additional = []; for (var _i = 1; _i < arguments.length; _i++) { additional[_i - 1] = arguments[_i]; } this._log(exports.NgxLoggerLevel.FATAL, message, additional); }; /** @deprecated customHttpHeaders is now part of the config, this should be updated via @see updateConfig */ NGXLogger.prototype.setCustomHttpHeaders = function (headers) { var config = this.getConfigSnapshot(); config.customHttpHeaders = headers; this.updateConfig(config); }; /** @deprecated customHttpParams is now part of the config, this should be updated via @see updateConfig */ NGXLogger.prototype.setCustomParams = function (params) { var config = this.getConfigSnapshot(); config.customHttpParams = params; this.updateConfig(config); }; /** @deprec