Best JavaScript code snippet using root
logger.ts
Source:logger.ts
1/* eslint-disable no-await-in-loop */2/* eslint-disable no-continue */3/* eslint-disable class-methods-use-this */4/* eslint-disable no-restricted-syntax */5/* eslint-disable no-param-reassign */6/* eslint-disable no-new */7/* eslint-disable no-underscore-dangle */8/* eslint-disable */9import Moment from "moment";10import SleepUtil from "./sleepUtil";11export enum LogLevel {12 Trace = "trace",13 Debug = "debug",14 Info = "info",15 Warning = "warning",16 Error = "error",17 None = "none"18}19export class LogOptions {20 sumoURL?: string | null = "";21 sendIntervalMs?: number = 2000;22 bufferSize?: number = 100;23 timeoutMs?: number = 10000;24 protocol?: string = "https";25 level: LogLevel = LogLevel.Info;26 // only error, warning, and info msgs will show - no debug or trace27 toConsole?: boolean = false;28}29export default class Logger {30 private static _theLogger: Logger;31 private messages: Array<any>;32 private closed = false;33 private options: LogOptions;34 private timer = -1;35 private levelStatuses: { [level: string]: boolean };36 public static CreateLogger(options: LogOptions) {37 if (Logger._theLogger !== undefined) {38 // This class is used as a singleton -- this should only be called once39 return;40 }41 // Create the logger42 // tslint:disable-next-line:no-unused-expression43 new Logger(options);44 }45 //46 // Static helper functions (fetch the instance for the caller)47 //48 public static trace(49 sourceFunction: string,50 message: string | any,51 data?: string | any,52 action?: string53 ): void {54 Logger.instance.log(LogLevel.Trace, sourceFunction, message, data, action);55 }56 public static debug(57 sourceFunction: string,58 message: string | any,59 data?: string | any,60 action?: string61 ): void {62 Logger.instance.log(LogLevel.Debug, sourceFunction, message, data, action);63 }64 public static info(65 sourceFunction: string,66 message: string | any,67 data?: string | any,68 action?: string69 ): void {70 Logger.instance.log(LogLevel.Info, sourceFunction, message, data, action);71 }72 public static warning(73 sourceFunction: string,74 message: string | any,75 data?: string | any,76 action?: string77 ): void {78 Logger.instance.log(79 LogLevel.Warning,80 sourceFunction,81 message,82 data,83 action84 );85 }86 public static error(87 sourceFunction: string,88 message: string | any,89 data?: string | any,90 action?: string91 ): void {92 Logger.instance.log(LogLevel.Error, sourceFunction, message, data, action);93 }94 //95 // Private static helpers96 //97 private static safeObjectToJSON(input: any): string {98 try {99 return JSON.stringify(input);100 } catch (error) {101 console.log(`Logger - Exception serializing log messages: ${error}`);102 return "";103 }104 }105 //106 // Public interface107 //108 public log(109 level: LogLevel,110 sourceFunction: string,111 message: string | any,112 data?: string | any,113 action?: string114 ): void {115 // Wrap a string with an Object116 if (typeof message === "string") {117 message = { message };118 }119 if (data) {120 // if (typeof data === 'object') {121 // data = JSON.stringify(data);122 // }123 message.data = data;124 } else {125 message.data = {};126 }127 // add metadata here128 this.addMetadata(message);129 if (action) {130 message.action = action;131 }132 message.level = level.toString();133 message.function = sourceFunction;134 if (this.levelStatuses[level] === true) {135 if (this.options.toConsole) {136 let msgToLog = `${Moment().format(137 "HH:mm:ss.SS"138 )} - ${level.toString()} - ${sourceFunction}() - ${message.message}`;139 if (message.data) {140 msgToLog += ` - ${JSON.stringify(message.data)}`;141 }142 console.log(msgToLog);143 }144 this.logInternal(message);145 }146 }147 public trace(148 sourceFunction: string,149 message: string | any,150 data?: string | any,151 action?: string152 ): void {153 this.log(LogLevel.Trace, sourceFunction, message, data, action);154 }155 public debug(156 sourceFunction: string,157 message: string | any,158 data?: string | any,159 action?: string160 ): void {161 this.log(LogLevel.Debug, sourceFunction, message, data, action);162 }163 public info(164 sourceFunction: string,165 message: string | any,166 data?: string | any,167 action?: string168 ): void {169 this.log(LogLevel.Info, sourceFunction, message, data, action);170 }171 public warning(172 sourceFunction: string,173 message: string | any,174 data?: string | any,175 action?: string176 ): void {177 this.log(LogLevel.Warning, sourceFunction, message, data, action);178 }179 public error(180 sourceFunction: string,181 message: string | any,182 data?: string | any,183 action?: string184 ): void {185 this.log(LogLevel.Error, sourceFunction, message, data, action);186 }187 //188 // Private helpers189 //190 private constructor(options: LogOptions) {191 this.messages = new Array<any>();192 this.options = new LogOptions();193 for (const prop in options) {194 // eslint-disable-next-line no-prototype-builtins195 if (options.hasOwnProperty(prop)) {196 // @ts-ignore197 this.options[prop] = options[prop];198 }199 }200 if (!this.options.bufferSize) {201 this.options.bufferSize = 1000;202 }203 this.levelStatuses = {};204 this.setupEnabledLevels(options.level);205 this.periodicUploaderAsync = this.periodicUploaderAsync.bind(this);206 Logger._theLogger = this;207 // Start the periodic uploads if SumoLogic URL was provided208 if (this.options.sumoURL) {209 this.periodicUploaderAsync();210 }211 }212 private async addMetadata(msg: any) {213 // add timestamp214 msg["timestamp"] = msg["timestamp"] || new Date().toISOString();215 const assignmentId = localStorage.getItem("assignmentId");216 const operatorId = localStorage.getItem("operatorId");217 if (assignmentId) {218 msg.assignmentId = assignmentId;219 }220 if (operatorId) {221 msg.operatorId = operatorId;222 }223 }224 private setupEnabledLevels(level: LogLevel) {225 switch (level) {226 case LogLevel.None:227 this.levelStatuses = {228 error: false,229 warning: false,230 info: false,231 debug: false,232 trace: false233 };234 break;235 case LogLevel.Error:236 this.levelStatuses = {237 error: true,238 warning: false,239 info: false,240 debug: false,241 trace: false242 };243 break;244 case LogLevel.Warning:245 this.levelStatuses = {246 error: true,247 warning: true,248 info: false,249 debug: false,250 trace: false251 };252 break;253 case LogLevel.Info:254 this.levelStatuses = {255 error: true,256 warning: true,257 info: true,258 debug: false,259 trace: false260 };261 break;262 case LogLevel.Debug:263 this.levelStatuses = {264 error: true,265 warning: true,266 info: true,267 debug: true,268 trace: false269 };270 break;271 case LogLevel.Trace:272 this.levelStatuses = {273 error: true,274 warning: true,275 info: true,276 debug: true,277 trace: true278 };279 break;280 default:281 this.levelStatuses = {282 error: true,283 warning: true,284 info: false,285 debug: false,286 trace: false287 };288 }289 }290 private async periodicUploaderAsync() {291 while (true) {292 if (this.messages.length > 0) {293 console.log(294 `Logger.periodicUploader - Sending ${this.messages.length} messages`295 );296 if (297 this.options.bufferSize &&298 this.messages.length > this.options.bufferSize299 ) {300 console.log(301 `Logger.periodicUploader - ${this.messages.length} messages exceeds buffer size of ${this.options.bufferSize}, not sending`302 );303 this.sendWarningMessageAsync();304 } else {305 await this.sendAsync();306 }307 }308 await SleepUtil.SleepAsync(this.options.sendIntervalMs);309 }310 }311 private logInternal(msg: any): void {312 if (this.closed) {313 throw new Error("Logger is already closed");314 }315 if (msg && msg !== "") {316 this.messages.push(msg);317 }318 // Check if it's time to send319 if (320 this.options.bufferSize &&321 this.messages.length >= this.options.bufferSize322 ) {323 this.trace("logInternal", "Logger - Buffer is full, sending messages");324 this.sendAsync();325 }326 }327 private payload(): string {328 let payload = "";329 for (let i = 0; i < this.messages.length; i += 1) {330 const message = Logger.safeObjectToJSON(this.messages[i]);331 if (message === "") continue;332 payload += `${message}\n`;333 }334 return payload;335 }336 private async sendWarningMessageAsync() {337 try {338 // Bail if we're not configured for upload339 if (!this.options.sumoURL) {340 // Clear the buffer341 this.messages = new Array<any>();342 return;343 }344 const message = {345 message: "Too many messages: buffer overflow hit",346 level: "ERROR",347 function: "sendWarningMessageAsync"348 };349 this.addMetadata(message);350 const msg = Logger.safeObjectToJSON(message);351 const payload = `${msg}\n`;352 const url = `${this.options.sumoURL}`;353 // Send the request354 const result = (await fetch(url, {355 method: "POST",356 body: payload357 // timeout: this.options.timeoutMs,358 })) as Response;359 // TODO: Eventually care about retrying if it fails...360 // NOTE: This just drops a chunk of logs on the floor if the upload fails361 if (!result.ok) {362 console.log(`Logger - Response not ok: ${result.status}`);363 } else {364 console.log("Logger - Upload appears to have worked");365 }366 } catch (error) {367 console.log(`Logger - Exception during upload: ${JSON.stringify(error)}`);368 }369 }370 private async sendAsync(): Promise<void> {371 try {372 // Bail if we're not configured for upload373 if (!this.options.sumoURL || this.options.sumoURL === "") {374 // Clear the buffer375 this.messages = new Array<any>();376 return;377 }378 const payload = this.payload();379 // Blank out the pending messages380 this.messages = new Array<any>();381 const url = `${this.options.sumoURL}`;382 // Send the request383 const result = (await fetch(url, {384 method: "POST",385 body: payload386 // timeout: this.options.timeoutMs,387 })) as Response;388 // TODO: Eventually care about retrying if it fails...389 // NOTE: This just drops a chunk of logs on the floor if the upload fails390 if (!result.ok) {391 console.log(`Logger - Response not ok: ${result.status}`);392 } else {393 console.log("Logger - Upload appears to have worked");394 }395 } catch (error) {396 console.log(`Logger - Exception during upload: ${JSON.stringify(error)}`);397 }398 }399 //400 // Public static interface401 //402 public static get instance(): Logger {403 return Logger._theLogger;404 }...
patch.js
Source:patch.js
1var utility = require('./utils');2module.exports = {3 method: method,4 methodsOf: methodsOf5};6function method(object, key) {7 var sourceFunction = object[key];8 return {9 with: withFactory(object, key, sourceFunction)10 }11}12function methodsOf(obj) {13 var keys = Object.keys(obj),14 length = keys.length,15 patch = {};16 for (var i = 0; i < length; i++) {17 var key = keys[i];18 if (utility.isFunction(obj[key])) {19 patch[key] = method(obj, key);20 }21 }22 return {23 with: function () {24 var keys = Object.keys(patch),25 length = keys.length,26 args = utility.asArray(arguments);27 for (var i = 0; i < length; i++) {28 var key = keys[i];29 obj.action = key;30 patch[key].with.apply(obj, args);31 }32 }33 }34}35function withFactory(object, key, sourceFunction) {36 var withFunction = function () {37 var args = utility.asArray(arguments);38 object[key] = function () {39 var argList = utility.asArray(arguments);40 return sourceFunction.apply(object, args.concat(argList));41 };42 };43 withFunction.decorator = function (decorate) {44 var args = utility.asArray(arguments).slice(1);45 object[key] = function () {46 return decorate.apply(object, [sourceFunction, object, key].concat(args));47 };48 };49 return withFunction;...
data-set-reload.js
Source:data-set-reload.js
1'use strict';2angular3 .module('refineryDashboard')4 .factory('dashboardDataSetsReloadService', [5 function () {6 return {7 /**8 * Placeholder method. Will be set by `setReload`.9 *10 * @method reload11 * @author Fritz Lekschas12 * @date 2016-05-0913 */14 reload: function () {},15 /**16 * Switch getter with a custom function.17 *18 * @method setReload19 * @author Fritz Lekschas20 * @date 2016-05-0921 *22 * @param {Function} sourceFunction The function to be set as23 * `reload`.24 */25 setReload: function (sourceFunction) {26 this.reload = sourceFunction;27 }28 };29 }...
Using AI Code Generation
1var root = require('root');2root.sourceFunction();3var child = require('child');4child.sourceFunction();5var root = require('root');6root.sourceFunction();7var child = require('child');8child.sourceFunction();9exports.sourceFunction = function(){10 console.log("This is source function");11}12exports.sourceFunction = function(){13 console.log("This is source function");14}15exports.sourceFunction = function(){16 console.log("This is source function");17 if(module.parent){18 module.parent.exports.sourceFunction();19 }20}
Using AI Code Generation
1var root = require('./root');2root.sourceFunction();3var source = require('./source');4exports.sourceFunction = source.sourceFunction;5exports.sourceFunction = function() {6 console.log('Hello World!');7};
Using AI Code Generation
1rootModule.sourceFunction();2subModule.sourceFunction();3subModule2.sourceFunction();4subModule3.sourceFunction();5subModule4.sourceFunction();6subModule5.sourceFunction();7subModule6.sourceFunction();8subModule7.sourceFunction();9subModule8.sourceFunction();10subModule9.sourceFunction();11subModule10.sourceFunction();12subModule11.sourceFunction();13subModule12.sourceFunction();14subModule13.sourceFunction();15subModule14.sourceFunction();16subModule15.sourceFunction();17subModule16.sourceFunction();18subModule17.sourceFunction();19subModule18.sourceFunction();20subModule19.sourceFunction();21subModule20.sourceFunction();22subModule21.sourceFunction();
Using AI Code Generation
1var myObj = {2 myMethod: function () {3 console.log('myMethod');4 }5};6var myObj2 = {7 myMethod: function () {8 console.log('myMethod2');9 }10};11var myObj3 = {12 myMethod: function () {13 console.log('myMethod3');14 }15};16var root = {17 sourceFunction: function (obj, methodName) {18 return obj[methodName].bind(obj);19 }20};21var myMethod = root.sourceFunction(myObj2, 'myMethod');22myMethod = root.sourceFunction(myObj3, 'myMethod');23var myObj = {24 myMethod: function () {25 console.log('myMethod');26 },27 sourceFunction: function (obj, methodName) {28 return obj[methodName].bind(obj);29 }30};31var myObj2 = {32 myMethod: function () {33 console.log('myMethod2');34 }35};36var myObj3 = {37 myMethod: function () {38 console.log('myMethod3');39 }40};41var myMethod = myObj.sourceFunction(myObj2, 'myMethod');42myMethod = myObj.sourceFunction(myObj3, 'myMethod');43var myObj = {44 myMethod: function () {45 console.log('myMethod');46 },47 sourceFunction: function (obj, methodName) {48 return obj[methodName].bind(obj);49 }50};51var myObj2 = {52 myMethod: function () {53 console.log('myMethod2');54 }55};56var myObj3 = {57 myMethod: function () {58 console.log('myMethod3');59 }60};61var myMethod = myObj.sourceFunction(myObj2, 'myMethod');62myMethod = myObj.sourceFunction(myObj3, 'myMethod');
Using AI Code Generation
1var root = require('../root');2var source = root.sourceFunction;3source();4exports.sourceFunction = function(){5 console.log("I am from source function");6}7var root = global.root;8var source = root.sourceFunction;9source();10global.root = {11 sourceFunction : function(){12 console.log("I am from source function");13 }14}15var root = global.root;16var source = root.sourceFunction;17source();18global.root = {19 sourceFunction : function(){20 console.log("I am from source function");21 }22}23var root = global.root;24var source = root.sourceFunction;25source();26global.root = {27 sourceFunction : function(){28 console.log("I am from source function");29 }30}31var root = global.root;32var source = root.sourceFunction;33source();34global.root = {35 sourceFunction : function(){36 console.log("I am from source function");37 }38}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!