How to use logObject method in Nightwatch

Best JavaScript code snippet using nightwatch

logTextParser.js

Source:logTextParser.js Github

copy

Full Screen

1/**2 * Parses text to return to the log items3 * Created by cos-caner on 12/4/15.4 * Remember to embed original_node, user, linked_node and template_node in api call i.e. var url = $osf.apiV2Url('nodes/' + nodeId + '/logs/', { query : { 'embed' : ['original_node', 'user']}});5 */6var m = require('mithril'); // exposes mithril methods, useful for redraw etc.7var logActions = require('json-loader!js/_allLogTexts.json');8var anonymousLogActions = require('json-loader!js/_anonymousLogTexts.json');9var $ = require('jquery'); // jQuery10var $osf = require('js/osfHelpers');11var Raven = require('raven-js');12var lodashGet = require('lodash.get');13var ravenMessagesCache = []; // Cache messages to avoid sending multiple times in one page view14var nodeCategories = require('json-loader!built/nodeCategories.json');15//Used when calling getContributorList to limit the number of contributors shown in a single log when many are mentioned16var numContributorsShown = 3;17/**18 * Utility function to not repeat logging errors to Sentry19 * @param message {String} Custom message for error20 * @param logObject {Object} the entire log object returned from the api21 */22function ravenMessage (message, logObject) {23 if(ravenMessagesCache.indexOf(message) === -1){24 Raven.captureMessage(message, {extra: {logObject: logObject}});25 ravenMessagesCache.push(message);26 }27}28/**29 * Checks if the required parameter to complete the log is returned30 * This may intentionally not be returned to make log anonymous31 * @param param {string|number} The parameter to be used32 * @param logObject {Object} the entire log object returned from the api33 * @returns {boolean}34 */35var paramIsReturned = function _paramIsReturned (param, logObject){36 if(!param){37 var message = 'Expected parameter for Log action ' + logObject.attributes.action + ' was not returned from log api.';38 ravenMessage(message, logObject);39 return false;40 }41 if (param.errors){42 return false;43 }44 return true;45};46var stripBackslash = function _stripBackslash(path){47 if (path.charAt(0) === '/') {48 path = path.substr(1, path.length - 1);49 }50 if (path.charAt(path.length - 1) === '/') {51 path = path.substr(0, path.length - 1);52 }53 return path;54};55/**56 * Returns the text parameters since their formatting is mainly the same57 * @param param {string} The parameter to be used, has to be available under logObject.attributes.param58 * @param text {string} The text to be used if param is not available59 * @param logObject {Object} the entire log object returned from the api60 * @returns {*}61 */62var returnTextParams = function (param, text, logObject, view_url) {63 var source = logObject.attributes.params[param];64 if(paramIsReturned(source, logObject)){65 if($.isArray(source)){66 return m('span', [67 source.map(function(item, index, arr){68 if(arr.length === 1 && index === 0){69 return m('span', item);70 }71 if(index === arr.length-1) {72 return m('span', ', and ' + item);73 }74 return m('span', item + ', ');75 })76 ]);77 }78 if (param === 'path'){79 source = stripBackslash(source);80 }81 // If the user changed the home page, display logText with capitalized82 // name to reflect how home is displayed to user.83 var type = logObject.attributes.action;84 if (type === 'wiki_updated' && source === 'home') {85 source = 'Home';86 }87 source = $osf.decodeText(source);88 return view_url ? m('a', {href: $osf.toRelativeUrl(view_url, window)}, source) : m('span', source);89 }90 return m('span', text);91};92/**93 * Returns a list of contributors to show in log as well as the trailing punctuation/text after each contributor.94 * If a contributor has a OSF profile, contributor is returned as a mithril link to user.95 * @param contributors {string} The list of contributors (OSF users or unregistered)96 * @param maxShown {int} the number of contributors shown before saying "and # others"97 * Note: if there is only 1 over maxShown, all contributors are shown98 * @returns {array}99 */100var getContributorList = function (contributors, maxShown){101 var contribList = [];102 var justOneMore = numContributorsShown === contributors.length -1;103 for(var i = 0; i < contributors.length; i++){104 var item = contributors[i];105 var comma = ' ';106 if(i !== contributors.length -1 && ((i !== maxShown -1) || justOneMore)){107 comma = ', ';108 }109 if(i === contributors.length -2 || ((i === maxShown -1) && !justOneMore) && (i !== contributors.length -1)) {110 if (contributors.length === 2)111 comma = ' and ';112 else113 comma = ', and ';114 }115 if (i === maxShown && !justOneMore){116 contribList.push([((contributors.length - i).toString() + ' others'), ' ']);117 return contribList;118 }119 if (item.active) {120 contribList.push([ m('a', {href: '/' + item.id + '/'}, item.full_name), comma]);121 }122 else {123 if (item.unregistered_name) {124 contribList.push([item.unregistered_name, comma]);125 } else {126 contribList.push([item.full_name, comma]);127 }128 }}129 return contribList;130};131var LogText = {132 view : function(ctrl, logObject) {133 var userInfoReturned = function(userObject){134 if (userObject){135 if (userObject.data){136 return true;137 }138 else if (userObject.errors[0].meta){139 return true;140 }141 }142 return false;143 };144 var logText = function() {145 var text = logActions[logObject.attributes.action];146 if (text) {147 if (logObject.anonymous) {148 return anonymousLogActions[logObject.attributes.action];149 } else if (text.indexOf('${user}') !== -1) {150 var userObject = logObject.embeds.user;151 if (userInfoReturned(userObject)) {152 return text;153 }154 else {155 var newAction = logObject.attributes.action + '_no_user';156 return logActions[newAction] ? logActions[newAction]: text;157 }158 } else {159 return text;160 }161 }162 return null;163 };164 var message = '';165 var text = logText();166 if(text){167 if (logObject.anonymous) { return m('span.osf-log-item', text); }168 var list = text.split(/(\${.*?})/);169 return m('span.osf-log-item', [170 list.map(function(piece){171 if (piece === '') {172 return m('span');173 }174 var startsWith = piece.substring(0,2);175 if(startsWith === '${'){176 var last = piece.length-1;177 var logComponentName = piece.substring(2,last);178 if(LogPieces[logComponentName]){179 return m.component(LogPieces[logComponentName], logObject);180 } else {181 message = 'There is no template in logTextParser.js for ' + logComponentName + '.';182 ravenMessage(message, logObject);183 return m('');184 }185 }186 return piece;187 })188 ]);189 } else {190 message = 'The log viewer has encountered an unexpected log action: ' + logObject.attributes.action +191 '. Please add a new log entry for this action to logActionsList.json' +192 ' and anonymousLogActionsList.json, or, if this log relates to an addon, ' +193 'to {addonName}LogActionList.json and {addonName}AnonymousLogActionList.json';194 ravenMessage(message, logObject);195 return m('em', 'Unable to retrieve log details');196 }197 }198};199var LogPieces = {200 // User that took the action201 user: {202 view: function (ctrl, logObject) {203 var userObject = logObject.embeds.user;204 var githubUser = logObject.attributes.params.github_user;205 if(paramIsReturned(userObject, logObject) && userObject.data) {206 return m('a', {href: $osf.toRelativeUrl(userObject.data.links.html, window), onclick: function() {207 $osf.trackClick(logObject.trackingCategory, logObject.trackingAction, 'navigate-to-user-from-logs');208 }}, userObject.data.attributes.full_name);209 }210 else if (userObject && userObject.errors[0].meta) {211 return m('span', userObject.errors[0].meta.full_name);212 }213 else if (githubUser){ //paramIsReturned skipped b/c this is applicable in only a few situtations214 return m('span', githubUser);215 }216 else {217 return m('span', 'A user');218 }219 }220 },221 // Node involved222 node: {223 view: function (ctrl, logObject) {224 var nodeObject = logObject.embeds.original_node;225 // Log action is node_removed226 if (logObject.attributes.action === 'node_removed') {227 if (logObject.attributes.params.params_node) {228 return m('span', $osf.decodeText(logObject.attributes.params.params_node.title));229 }}230 else if(paramIsReturned(nodeObject, logObject) && nodeObject.data){231 if (nodeObject.data.links && nodeObject.data.attributes) {232 return m('a', {href: $osf.toRelativeUrl(nodeObject.data.links.html, window), onclick: function() {233 $osf.trackClick(logObject.trackingCategory, logObject.trackingAction, 'navigate-to-project-from-logs');234 }}, $osf.decodeText(nodeObject.data.attributes.title));235 }236 else if (nodeObject.data.attributes) {237 return m('span', $osf.decodeText(nodeObject.data.attributes.title));238 }239 }240 // Original node has been deleted241 else if (!paramIsReturned(nodeObject, logObject)) {242 var deletedNode = logObject.attributes.params.params_node;243 if (paramIsReturned(deletedNode, logObject)){244 return m('span', $osf.decodeText(deletedNode.title));245 }246 }247 return m('span', 'a project');248 }249 },250 // Contributor list of added, updated etc.251 contributors: {252 view: function (ctrl, logObject) {253 var contributors = logObject.attributes.params.contributors;254 if(paramIsReturned(contributors, logObject)) {255 return m('span', getContributorList(contributors, numContributorsShown));256 }257 return m('span', 'some users');258 }259 },260 // The tag added to item involved261 tag: {262 view: function (ctrl, logObject) {263 var tag = logObject.attributes.params.tag;264 if(paramIsReturned(tag, logObject)) {265 return m('a', {href: '/search/?q=%22' + tag + '%22'}, tag);266 }267 return m('span', '');268 }269 },270 // Original node271 forked_from: {272 view: function(ctrl, logObject) {273 var forkedFrom = logObject.attributes.params.params_node;274 var id = forkedFrom.id;275 var title = $osf.decodeText(forkedFrom.title);276 if (paramIsReturned(forkedFrom, logObject) && title){277 if (id) {278 return m('a', {href: '/' + id + '/' }, title);279 }280 return m('span', title);281 }282 return m('span', 'a project');283 }284 },285 // Node that is linked to the node involved286 pointer: {287 view: function (ctrl, logObject) {288 var linked_node = logObject.embeds.linked_node;289 if (linked_node && paramIsReturned(linked_node, logObject) && !linked_node.errors) {290 return m('a', {href: $osf.toRelativeUrl(linked_node.data.links.html, window)}, $osf.decodeText(linked_node.data.attributes.title));291 }292 var linked_registration = logObject.embeds.linked_registration;293 if (linked_registration && paramIsReturned(linked_registration, logObject) && !linked_registration.errors) {294 return m('a', {href: $osf.toRelativeUrl(linked_registration.data.links.html, window)}, $osf.decodeText(linked_registration.data.attributes.title));295 }296 return m('span', 'a project');297 }298 },299 // Pointer category300 pointer_category: {301 view: function (ctrl, logObject) {302 var linked_node = logObject.embeds.linked_node;303 var category = '';304 if (linked_node && paramIsReturned(linked_node, logObject) && !linked_node.errors) {305 category = linked_node.data.attributes.category;306 if (category !== '') {307 return m('span', linked_node.data.attributes.category);308 }309 }310 var linked_registration = logObject.embeds.linked_registration;311 if (linked_registration && paramIsReturned(linked_registration, logObject) && !linked_registration.errors) {312 category = linked_registration.data.attributes.category;313 if (category !== '') {314 return m('span', linked_registration.data.attributes.category);315 }316 }317 return m('span', '');318 }319 },320 // Node that acted as template to create a new node involved321 template: {322 view: function (ctrl, logObject) {323 var template_node = logObject.embeds.template_node;324 if(paramIsReturned(template_node, logObject)){325 return m('a', {href: $osf.toRelativeUrl(template_node.data.links.html, window)}, $osf.decodeText(template_node.data.attributes.title));326 }327 var templateFromParams = logObject.attributes.params.template_node;328 if (paramIsReturned(templateFromParams, logObject && templateFromParams.title)){329 return m('span', $osf.decodeText(templateFromParams.title));330 }331 return m('span','a project' );332 }333 },334 // The original title of node involved335 title_original: {336 view: function (ctrl, logObject) {337 return returnTextParams('title_original', 'a title', logObject);338 }339 },340 // The new title of node involved341 title_new: {342 view: function (ctrl, logObject) {343 var url = null;344 var nodeObject = logObject.embeds.original_node;345 if (paramIsReturned(nodeObject, logObject && nodeObject.data)){346 url = lodashGet(nodeObject, 'data.links.html', null);347 }348 return returnTextParams('title_new', 'a title', logObject, url);349 }350 },351 // Update fields for the node352 updated_fields: {353 view: function (ctrl, logObject) {354 var updatedFieldsParam = logObject.attributes.params.updated_fields;355 if (paramIsReturned(updatedFieldsParam, logObject)) {356 var updatedField = Object.keys(updatedFieldsParam)[0];357 if (updatedField === 'category'){358 return m('span', updatedField + ' to ' + nodeCategories[updatedFieldsParam[updatedField].new]);359 }360 return m('span', updatedField + ' to ' + updatedFieldsParam[updatedField].new);361 }362 return m('span', 'field');363 }},364 // external identifiers on node365 identifiers: {366 view: function (ctrl, logObject) {367 external_ids = logObject.attributes.params.identifiers;368 if (paramIsReturned(external_ids, logObject)) {369 var doi = external_ids.doi;370 var ark = external_ids.ark;371 if (doi && ark) {372 return m('span', 'doi:' + doi + ' and ark:' + ark);373 }374 if (doi) {375 return m('span', 'doi:' + doi);376 }377 if (ark) {378 return m('span', 'ark:' + ark );379 }380 }381 return m('span', '');382 }383 },384 // Wiki page name385 page: {386 view: function (ctrl, logObject) {387 var url = null;388 var action = logObject.attributes.action;389 var acceptableLinkedItems = ['wiki_updated', 'wiki_renamed'];390 var page_id = logObject.attributes.params.page_id;391 if (acceptableLinkedItems.indexOf(action) !== -1) {392 if (paramIsReturned(page_id, logObject)){393 url = '/' + page_id;394 }395 }396 return returnTextParams('page', 'a title', logObject, url);397 }398 },399 // Old wiki title that's renamed400 old_page: {401 view: function (ctrl, logObject) {402 return returnTextParams('old_page', 'a title', logObject);403 }404 },405 // Wiki page version406 version: {407 view: function (ctrl, logObject) {408 var version = logObject.attributes.params.version;409 if(paramIsReturned(version, logObject)){410 return m('span', version);411 }412 return m('span', '#');413 }414 },415 //416 source: {417 view: function (ctrl, logObject) {418 var source = logObject.attributes.params.source;419 if(paramIsReturned(source, logObject)){420 var sourceMaterialized = stripBackslash(source.materialized);421 return m('span', [sourceMaterialized, ' in ', source.addon]);422 }423 return m('span','a name/location' );424 }425 },426 //427 destination: {428 view: function (ctrl, logObject) {429 var destination = logObject.attributes.params.destination;430 if(paramIsReturned(destination, logObject)){431 var destinationMaterialized = destination.materialized;432 if (destinationMaterialized.endsWith('/')){433 destinationMaterialized = stripBackslash(destination.materialized);434 return m('span', [destinationMaterialized, ' in ', destination.addon]);435 }436 return m('span', [m('a', {href: $osf.toRelativeUrl(destination.url, window)}, destinationMaterialized), ' in ', destination.addon]);437 }438 return m('span','a new name/location' );439 }440 },441 //442 kind: {443 view: function (ctrl, logObject) {444 return returnTextParams('kind', '', logObject);445 }446 },447 //448 path: {449 controller: function(logObject){450 var self = this;451 self.returnLinkForPath = function(logObject) {452 if (logObject) {453 var action = logObject.attributes.action;454 var acceptableLinkedItems = ['osf_storage_file_added', 'osf_storage_file_updated', 'file_tag_added', 'file_tag_removed',455 'github_file_added', 'github_file_updated', 'box_file_added', 'box_file_updated', 'dropbox_file_added', 'dropbox_file_updated',456 's3_file_added', 's3_file_updated', 'figshare_file_added', 'checked_in', 'checked_out'];457 if (acceptableLinkedItems.indexOf(action) !== -1 && logObject.attributes.params.urls) {458 return logObject.attributes.params.urls.view;459 }460 }461 return null;462 };463 },464 view: function (ctrl, logObject) {465 var url = ctrl.returnLinkForPath(logObject);466 return returnTextParams('path', 'a file', logObject, url);467 }468 },469 //470 filename: {471 controller: function(logObject) {472 var self = this;473 self.returnLinkForPath = function(logObject){474 if (logObject){475 var action = logObject.attributes.action;476 var acceptableLinkedItems = ['dataverse_file_added'];477 if (acceptableLinkedItems.indexOf(action) !== -1 && logObject.attributes.params.urls) {478 return logObject.attributes.params.urls.view;479 }480 }481 return null;482 };483 },484 view: function (ctrl, logObject) {485 var url = ctrl.returnLinkForPath(logObject);486 return returnTextParams('filename', 'a title', logObject, url);487 }488 },489 folder: {490 view: function(ctrl, logObject) {491 return returnTextParams('folder', 'a folder', logObject);492 }493 },494 repo: {495 view: function(ctrl, logObject) {496 var github_user = logObject.attributes.params.github_user;497 var github_repo = logObject.attributes.params.github_repo;498 if (paramIsReturned(github_repo, logObject) && paramIsReturned(github_user, logObject)){499 return m('span', github_user + '/' + github_repo);500 }501 return m('span', '');502 }503 },504 bitbucket_repo: {505 view: function(ctrl, logObject) {506 var bitbucketUser = logObject.attributes.params.bitbucket_user;507 var bitbucketRepo = logObject.attributes.params.bitbucket_repo;508 if (paramIsReturned(bitbucketRepo, logObject) && paramIsReturned(bitbucketUser, logObject)){509 return m('span', bitbucketUser + '/' + bitbucketRepo);510 }511 return m('span', '');512 }513 },514 folder_name: {515 view: function(ctrl, logObject) {516 return returnTextParams('folder_name', 'a folder', logObject);517 }518 },519 bucket: {520 view: function(ctrl, logObject) {521 return returnTextParams('bucket', 'a bucket', logObject);522 }523 },524 forward_url: {525 view: function(ctrl, logObject) {526 var url = logObject.attributes.params.forward_url;527 return returnTextParams('forward_url', 'a new URL', logObject, url);528 }529 },530 box_folder: {531 view: function(ctrl, logObject) {532 var folder = logObject.attributes.params.folder_name;533 if(paramIsReturned(folder, logObject)){534 return m('span', folder === 'All Files' ? '/ (Full Box)' : folder);535 }536 return m('span', '');537 }538 },539 dropbox_folder: {540 view: function(ctrl, logObject) {541 var folder = logObject.attributes.params.folder;542 if(paramIsReturned(folder, logObject)){543 return m('span', folder === '/' ? '/ (Full Dropbox)' : folder);544 }545 return m('span', '');546 }547 },548 onedrive_folder: {549 view: function(ctrl, logObject) {550 var folder = logObject.attributes.params.folder;551 if(paramIsReturned(folder, logObject)){552 return m('span', folder === '/' ? '/ (Full OneDrive)' : folder);553 }554 return m('span', '');555 }556 },557 citation: {558 view: function(ctrl, logObject) {559 return returnTextParams('citation_name', '', logObject);560 }561 },562 dataset: {563 view: function(ctrl, logObject){564 return returnTextParams('data_set', '', logObject);565 }566 },567 study: {568 view: function(ctrl, logObject){569 return returnTextParams('study', '', logObject);570 }571 },572 googledrive_path: {573 controller: function(logObject){574 var self = this;575 self.returnLinkForPath = function(logObject) {576 if (logObject) {577 var action = logObject.attributes.action;578 var acceptableLinkedItems = ['googledrive_file_added', 'googledrive_file_updated'];579 if (acceptableLinkedItems.indexOf(action) !== -1 && logObject.attributes.params.urls) {580 return logObject.attributes.params.urls.view;581 }582 }583 return null;584 };585 },586 view: function (ctrl, logObject) {587 var url = ctrl.returnLinkForPath(logObject);588 var path = logObject.attributes.params.path;589 if(paramIsReturned(path, logObject)){590 path = stripBackslash(path);591 if (url) {592 return m('a', {href: $osf.toRelativeUrl(url, window)}, path);593 }594 return m('span', path);595 }596 return m('span', '');597 }598 },599 path_type: {600 view: function(ctrl, logObject){601 var path = logObject.attributes.params.path;602 if (paramIsReturned(path, logObject)) {603 if (path.slice(-1) === '/') {604 return m('span', 'folder');605 }606 }607 return m('span', 'file');608 }609 },610 googledrive_folder: {611 view: function(ctrl, logObject){612 var folder = logObject.attributes.params.folder;613 if(paramIsReturned(folder, logObject)){614 return m('span', folder === '/' ? '(Full Google Drive)' : folder);615 }616 return m('span', '');617 }618 },619 addon: {620 view: function(ctrl, logObject){621 return returnTextParams('addon', '', logObject);622 }623 },624 institution: {625 view: function(ctrl, logObject){626 var institution = logObject.attributes.params.institution;627 if (paramIsReturned(institution, logObject)){628 if (institution.id !== null) {629 return m('a', {'href': '/institutions/' + institution.id + '/'}, institution.name);630 }631 return m('span', institution.name);632 }633 return m('span', 'an institution');634 }635 },636 comment_location: {637 view: function(ctrl,logObject){638 var file = logObject.attributes.params.file;639 var wiki = logObject.attributes.params.wiki;640 // skip param.isReturned as not having a file or wiki is expected at times641 // Comment left on file642 if (file){643 return m('span', ['on ', m('a', {href: $osf.toRelativeUrl(file.url, window)}, file.name)]);644 }645 // Comment left on wiki646 if (wiki) {647 var name = (wiki.name === 'home') ? 'Home' : wiki.name;648 return m('span', ['on wiki page ', m('a', {href: $osf.toRelativeUrl(wiki.url, window)}, name)]);649 }650 // Comment left on project651 return m('span', '');652 }653 },654 preprint: {655 view: function(ctrl, logObject){656 var preprint = logObject.attributes.params.preprint;657 if (paramIsReturned(preprint, logObject)) {658 return m('a', {href: '/' + preprint}, 'preprint');659 }660 return m('span', 'preprint');661 }662 },663 preprint_provider: {664 view: function(ctrl, logObject){665 var preprint_provider = logObject.attributes.params.preprint_provider;666 if (paramIsReturned(preprint_provider, logObject)) {667 return m('a', {href: preprint_provider.url}, preprint_provider.name);668 }669 return m('span', '');670 }671 },672 license: {673 view: function(ctrl, logObject){674 var license_name = logObject.attributes.params.license;675 if (license_name) {676 return m('span', 'to ' + license_name);677 }678 return m('span', '');679 }680 },681 anonymous_link: {682 view: function(ctrl, logObject) {683 if (logObject.attributes.params.anonymous_link) {684 return m('span', 'an anonymous');685 }686 return m('span', 'a');687 }688 },689 gitlab_repo: {690 view: function(ctrl, logObject){691 var gitlab_user = logObject.attributes.params.gitlab_user;692 var gitlab_repo = logObject.attributes.params.gitlab_repo;693 if (paramIsReturned(gitlab_repo, logObject) && paramIsReturned(gitlab_user, logObject)) {694 return m('span', gitlab_user + '/' + gitlab_repo);695 }696 return m('span', '');697 }698 },699};700module.exports = {701 LogText:LogText,702 getContributorList: getContributorList...

Full Screen

Full Screen

httpCallsHandler.js

Source:httpCallsHandler.js Github

copy

Full Screen

1///**2// * Created by harihar on 11/04/16.3// */4//5//// Http post to another server ip.6//var request = require('request');7//var httpTransactions = require('../database/models/httpTransactions');8//var failedHttpTransactions = require('../database/models/failedHttpTransactions');9//var httpCallsConfig = require('../config/httpCallsConfiguration');10//var constants = require('../config/constants');11//var logger = require('../logger/logger.js').getLogger('httpCallsHandler');12//13//14//var currentURL = constants.INTER_SERVER_HTTP_POST_URL;15//logger.info('HTTP post url set to : ' ,currentURL);16//17//var retryTimer ;18//19//var postToURL = function postToURL(url , body , method , cb) {20//21//22// var options = {};23// options.body = body;24// options.json = true;25// options.url = url;26// options.method = method;27// options.timeout = 60000;28//29// logger.info('Received postToURL request.Options object ='+ JSON.stringify(options));30//31// request(url, options, function (error, response) {32//33// var logObject = {};34// logObject.tranx_type = body.request_type;35// logObject.request_url = url;36// logObject.sender_ip = 'localhost';37// logObject.receiver_ip = currentURL;38//39//40// if (error) {41//42// logObject.status_code = '500';43// logObject.message = 'SERVER ERROR : Http request failed.';44//45// logFailedTransactionToDB(logObject, function(err ,done){46// cb(error, response);47// });48// retryHttpRequest(logObject);49// }50// else {51//52// // cancel setTimeout() if any , on response received.53// clearTimeout(retryTimer);54//55// logObject.status_code = response.statusCode;56// logObject.message = 'Http request successfull for '+ logObject.tranx_type;57//58// logTransactiontoDB(logObject,function(err ,done){59// cb(error, response);60// });61//62// }63//64// });65//};66//67//68//69//70//var retryCounter = 0;71//var retryDelay = 2000; // milliseconds72//73//function retryHttpRequest(body){74// if(retryCounter > 5 ){75// logger.info('RETRIED POST TO URL ' + retryCounter + ' TIMES.Logging to database...\n');76// logTransactiontoDB(err,null);77// }78// else {79// retryCounter++;80// retryTimer = setTimeout(postToURL(body),retryDelay);81// }82//}83//84//85//function logTransactiontoDB(logObject ,cb) {86//87// var transxnObj = {};88//89// transxnObj.tranx_type = logObject.tranx_type;90// transxnObj.status_code = logObject.status_code;91// transxnObj.message = logObject.message;92// transxnObj.request_url = logObject.request_url;93// transxnObj.sender_ip = logObject.sender_ip;94// transxnObj.receiver_ip = logObject.receiver_ip;95// transxnObj.timeStamp = new Date().getTime();96//97// var httpTranxn = new httpTransactions(transxnObj); // create new schema instance of httpTransactions98//99// httpTranxn.save( function (err, queryResult) {100// if (err) {101// logger.error("Unable to log request to database !!!",err);102// cb(err,null);103// }104// else {105// logger.info("Http inter server transaction of type : "+ logObject.tranx_type + " successfully logged to database .Transaction id: ",queryResult._id.toString());106// cb(null,true);107// }108// });109//110//}111//112//var makeHttpRequest = function makeHttpRequest(data , method, cb){113//114// var url ;115// var requestType = data.requestType ;116// var payLoad = data.payLoad;117// var body;118//119// url = currentURL + '/send-data';120// body = {"request_type": requestType};121// if(payLoad)122// {123// body['data'] = payLoad;124// }125// method = 'post';126//127// postToURL(url,body,method,function(err,resp){128// if(err){129// cb(err,null);130// }131// else {132// cb(null,resp);133// }134// });135//136//};137//138//139//140//141//// HTTP CALLS FOR QA TO LIVE SERVER142//143//144//sendDataToLiveServer = function sendDataToLive(data ,url ,method, cb) {145//146// var options = {};147// options.body = data;148// options.json = true;149// options.url = url;150// options.method = method;151// // options.timeout = 5000;152//153// request(url, options, function (error, response) {154//155// if (error) {156// // console.log("error", error);157// cb(error,null);158// }159// else {160// // console.log('response', response);161// cb(null,response.body)162// }163//164// });165//166//167//};168//169//170//function logFailedTransactionToDB(logObject){171// var transxnObj = {};172//173// transxnObj.tranx_type = logObject.tranx_type;174// transxnObj.tranx_id = new Date().getTime().toString(12);175// transxnObj.status_code = logObject.status_code;176// transxnObj.message = logObject.message;177// transxnObj.request_url = logObject.request_url;178// transxnObj.sender_ip = logObject.sender_ip;179// transxnObj.receiver_ip = logObject.receiver_ip;180// transxnObj.timeStamp = new Date().getTime();181//182// var failedHttpTranxn = new failedHttpTransactions(transxnObj); // create new schema instance of FailedHttpTransactions183//184// failedHttpTranxn.save( function (err, queryResult) {185// if (err) {186// logger.error("Unable to log request to database !!!",err);187// cb(err,null);188// }189// else {190// logger.info("Http inter server transaction of type : "+ logObject.tranx_type + " successfully logged to database .Transaction id: ",queryResult._id.toString());191// cb(null,true);192// }193// });194//195//}196//197//198///**199// * MODULE EXPORTS200// */201//202//module.exports.postToURL = postToURL;203//module.exports.makeHttpRequest = makeHttpRequest ;204//module.exports.sendDataToLiveServer = sendDataToLiveServer ;205//206//207//208//209// Http post to another server .210var request = require('request');211var httpTransactions = require('../database/models/httpTransactions');212var constants = require('../config/constants');213var logger = require('../logger/logger.js').getLogger('httpCallsHandler');214var httpCallsConfig = require('../config/httpCallsConfiguration.js');215var emailUtility = require('../utils/emailUtility');216var currentURL = constants.INTER_SERVER_HTTP_POST_URL;217//var currentURL = 'http://52.86.35.40:4000';//testing purpose...fake ip218logger.info('HTTP post url set to : ' ,currentURL);219var retryTimer ;220var timeout_handles ={};221var postToURL = function postToURL(requestParams, cb) {222 var options = {};223 if (typeof requestParams.request_body === 'string')224 requestParams.request_body = JSON.parse(requestParams.request_body);225 options.body = requestParams.request_body;226 options.json = true;227 options.url = requestParams.request_url;228 options.method = requestParams.request_method;229 options.timeout = retryDelay; // Time in milliseconds ...230 console.log("Request Body : ", JSON.stringify(options.body));231 if (Object.keys(timeout_handles).length !== 0 && timeout_handles.constructor === Object){232 if (requestParams.request_body.request_type === requestParams.retryTimerId) {233 console.log("Deleting key ", requestParams.retryTimerId);234 clearTimeout(timeout_handles[requestParams.retryTimerId]);235 delete timeout_handles[requestParams.retryTimerId];236 }237 }238 request(options.url, options, function (error, response) {239 var logObject = {};240 logObject.tranx_type = requestParams.request_body.request_type;241 logObject.request_body = JSON.stringify(requestParams.request_body);242 logObject.request_url = requestParams.request_url;243 logObject.tranx_id = requestParams.tranx_id ;244 logObject.sender_ip = 'localhost';245 logObject.receiver_ip = currentURL;246 logObject.request_method = requestParams.request_method;247 logObject.retryTimerId = requestParams.retryTimerId;248 if (error) {249 logObject.status_code = '500';250 logObject.request_status = constants.HTTP_REQUEST_STATUS.RETRYING;251 logObject.message = 'SERVER ERROR : Http request failed.';252 logTransactiontoDB(logObject, function(err ,done){253 if(err){254 logger.error('unable to log transaction type %s to db ',logObject.tranx_type,err);255 cb(err,{statusCode:500});256 }else{257 done.retryTimerId = logObject.retryTimerId;258 if(done.retryCount == 0){259 logger.info("Sending Response back to client : ",{statusCode:500});260 cb(null, {statusCode:500});261 }262 if(done.retryCount <=5){263 logger.error('Retrying...',done.retryCount);264 retryHttpRequest(done);265 }266 }267 });268 }269 else {270 if (logObject.tranx_type === httpCallsConfig.DELETE_USER_FROM_REDIS && logObject.tranx_id) {271 removeProfileViewLog(logObject.tranx_id);272 }273 logger.info('Inter Server Http Request with body %s for type %s was successful.Status Code : ', JSON.stringify(options.body), logObject.tranx_type, 200);274 if(logObject.tranx_type === httpCallsConfig.USER_PROFILE_PIC_UPDATED){275 // console.log("Response Body for Profilepic " ,response.body);276 cb(null, {statusCode: 200,image_text_version:response.body.image_text_version});277 }else{278 cb(null, {statusCode: 200});279 }280 }281 });282};283function removeProfileViewLog(tranxnId) {284 // var profileViewArray = requestBody.data.profileViewArray;285 // console.log(profileViewArray);286 httpTransactions.remove({tranx_id: tranxnId}, function (err, logRecord) {287 if (err) {288 logger.error("Error deleting failed http transaction", err);289 } else {290 logger.info("Successfully deleted Failed http transaction after successful update");291 }292 });293}294var retryDelay = 5000; // milliseconds295function retryHttpRequest(logObject){296 if( timeout_handles[logObject.retryTimerId])297 {298 // console.log("Deleting key ",logObject.retryTimerId);299 clearTimeout( timeout_handles[logObject.retryTimerId] );300 delete timeout_handles[logObject.retryTimerId];301 }302 if(logObject.retryCount && logObject.retryCount == 5 ) {303 logger.info('RETRIED POST TO URL ' + logObject.retryCount + ' TIMES.Logging to database...\n');304 //send email to admin305 emailUtility.sendEmail('nikhil@lambentgamestudio.com',306 'HTTP request failed on server : '+constants.SERVER_IP.toString(),307 'Retried Http request of type : '+ logObject.tranx_type + ' with id : ' + logObject.tranx_id, function (err, resp) {308 if (err) {309 logger.err("Unable to lodge email to admin", err);310 } else {311 logger.info('Email successfully sent to admin');312 }313 });314 logger.info("Retried request with id : %s upto %s times .Sending mail to admin. ", logObject.tranx_id, logObject.retryCount);315 }316 else if(logObject.retryCount && logObject.retryCount < 5 ) {317 logObject["retryTimerId"] = logObject.tranx_type;318 logger.info("Retrying type %s again after",logObject.tranx_type,retryDelay);319 retryTimer = setTimeout(postToURL(logObject),retryDelay);320 timeout_handles[logObject.tranx_type] = retryTimer;321 }322}323function logTransactiontoDB(logObject ,cb) {324 httpTransactions.findOne({tranx_id: logObject.tranx_id}, function (err, logRecord) {325 if (err) {326 logger.error("error finding failed http transaction",err);327 cb(err,null);328 } else {329 if (logRecord) {330 // Failed Record exists , update it331 logRecord.request_body = logObject.request_body;332 logRecord.retryCount ++;333 logRecord.timestamp = new Date();334 logRecord.save(function(err,done){335 if (err) {336 logger.error("Unable to log request to database !!!", err.stack);337 cb(err, null);338 }339 else {340 logger.info("Http inter server transaction of type : " + logRecord.tranx_type + " successfully updated to database .Transaction id: ", logRecord._id.toString());341 cb(null, logRecord.toJSON());342 }343 });344 } else {345 // Add new failed record.346 var transxnObj = {};347 transxnObj.tranx_id = new Date().getTime().toString(12);348 transxnObj.tranx_type = logObject.tranx_type;349 transxnObj.retryCount = 1;350 transxnObj.request_method = logObject.request_method;351 transxnObj.request_body = logObject.request_body;352 transxnObj.status_code = logObject.status_code;353 transxnObj.message = logObject.message;354 transxnObj.request_url = logObject.request_url;355 transxnObj.sender_ip = logObject.sender_ip;356 transxnObj.receiver_ip = logObject.receiver_ip;357 transxnObj.timeStamp = new Date().getTime();358 var httpTranxn = new httpTransactions(transxnObj); // create new schema instance of httpTransactions359 httpTranxn.save(function (err, queryResult) {360 if (err) {361 logger.error("Unable to log request to database !!!", err.stack);362 cb(err, null);363 }364 else {365 logger.info("Http inter server transaction of type : " + logObject.tranx_type + " successfully logged to database .Transaction id: ", queryResult._id.toString());366 cb(null, queryResult.toJSON());367 }368 });369 }370 }371 });372}373var makeHttpRequest = function makeHttpRequest(data , method, cb){374 var url ;375 var requestType = data.requestType ;376 var payLoad = data.payLoad;377 var body;378 url = currentURL + '/send-data';379 body = {"request_type": requestType};380 if(payLoad)381 {382 body['data'] = payLoad;383 }384 method = 'post';385 // console.log("Body Received: ",JSON.stringify(body));386 var reqObject ={};387 reqObject.request_url = url;388 reqObject.request_body = body;389 reqObject.request_method = method;390 reqObject.tranx_id = null;391 checkForExistingRequestInQueue(requestType,function(err,res){392 if(err){393 cb(err,null);394 }else{395 if(res === false){396 postToURL(reqObject,function(err,resp){397 if(err){398 cb(err,null);399 }400 else {401 cb(null,resp);402 }403 });404 }else{405 res.retryCount = 0;406 if(res.tranx_type == httpCallsConfig.DELETE_USER_FROM_REDIS )407 {408 var rb = JSON.parse(res.request_body);409 // console.log("RB == > ",rb.data.profileViewArray,typeof rb.data.profileViewArray ,rb.data.profileViewArray.length);410 var flag = 1 ;411 for(var index =0;index < rb.data.profileViewArray.length ;index++) {412 // console.log("index---",index);413 if (rb.data.profileViewArray[index].id == body.data.profileViewArray[0].id) {414 console.log("*****Match Found*****");415 rb.data.profileViewArray[index].profile_view += body.data.profileViewArray[0].profile_view;416 flag = 0;417 break;418 }419 }420 if(flag === 1){421 console.log("***NO Match Found****");422 rb.data.profileViewArray.push(body.data.profileViewArray[0]);423 }424 reqObject.request_body = rb;425 res.request_body = JSON.stringify(rb);426 // console.log("NEW RES : === ",res );427 }428 res.save(function(err,result){429 if(err){430 cb(err,null);431 }else {432 reqObject.tranx_id = res.tranx_id;433 postToURL(reqObject, function (err, resp) {434 if (err) {435 cb(err, null);436 }437 else {438 cb(null, resp);439 }440 });441 }442 });443 }444 }445 });446};447function checkForExistingRequestInQueue(requestType,cb) {448 httpTransactions.findOne({tranx_type: requestType}, function (err, resp) {449 if(err){450 cb(err,null);451 }else{452 if(resp){453 cb(null,resp);454 }else{455 cb(null,false);456 }457 }458 });459}460// HTTP CALLS FOR QA TO LIVE SERVER461var sendDataToLiveServer = function sendDataToLive(data ,url ,method, cb) {462 var options = {};463 options.body = data;464 options.json = true;465 options.url = url;466 options.method = method;467 // options.timeout = 5000;468 request(url, options, function (error, response) {469 if (error) {470 // console.log("error", error);471 cb(error,null);472 }473 else {474 // console.log('response', response);475 cb(null,response.body)476 }477 });478};479/**480 * MODULE EXPORTS481 */482module.exports.postToURL = postToURL;483module.exports.makeHttpRequest = makeHttpRequest ;...

Full Screen

Full Screen

loggingsystem.js

Source:loggingsystem.js Github

copy

Full Screen

1const Discord = require("discord.js");2const moment = require("moment");3const bot = require('../CorruptionBot.js')4//#region Message logging5module.exports.MessageDeleted = (client, message, sqlcon) => {6 GetLoggingStatus(sqlcon, message.guild.id, function (LogObject) {7 setTimeout(function () {8 if (!LogObject.MessageLogging || !LogObject.MessageLoggingChannel) return9 let logs = message.guild.fetchAuditLogs({ type: 72 }).catch(O_o => { });10 let mlogchannel = message.guild.channels.find((channel => channel.id === LogObject.MessageLoggingChannel));11 if (mlogchannel == null) return12 if (message.member == null || message.member.displayHexColor == null) color = '#6fa1f2'13 else color = message.member.displayHexColor14 const sInfo = new Discord.RichEmbed()15 .setAuthor(`${message.author.tag} - Deleted message`, message.author.avatarURL)16 .setColor(color)17 .setTimestamp()18 .addField("Channel", message.channel, true);19 if (logs.entries != undefined) {20 let entry = logs.entries.first();21 if (entry.createdTimestamp > (Date.now() - 5000)) sInfo.addField("Deleted By", entry.executor, true)22 }23 if (message.attachments.first() !== undefined) {24 let aName = message.attachments.first().filename25 sInfo.addField("Attatchment", aName, true)26 }27 if (message.content) sInfo.setDescription(message.content)28 mlogchannel.send(sInfo).catch(O_o => { console.log("ERROR!!!!!") });29 }, 250)30 })31}32module.exports.MessageEdited = (client, oldMSG, newMSG, sqlcon) => {33 GetLoggingStatus(sqlcon, oldMSG.guild.id, function (LogObject) {34 if (!LogObject.MessageLogging || !LogObject.MessageLoggingChannel) return35 let mlogchannel = oldMSG.guild.channels.find((channel => channel.id === LogObject.MessageLoggingChannel));36 if (mlogchannel == null) return;37 let color = oldMSG.member.displayHexColor;38 if (color == null) color = "#e450f4";39 if (oldMSG.toString().length > 1024) oldMSG = oldMSG.toString().slice(1023);40 if (newMSG.toString().length > 1024) newMSG = newMSG.toString().slice(1023);41 const sInfo = new Discord.RichEmbed()42 .setAuthor(`${oldMSG.member.tag} - Message Edited`, oldMSG.author.avatarURL)43 .setDescription(oldMSG)44 .setColor(color)45 .setTimestamp()46 .addField("New message:", `${newMSG}`)47 .addField("Channel", oldMSG.channel);48 mlogchannel.send(sInfo).catch(O_o => { });49 })50}51//#endregion52//#region Member logging53module.exports.MemberAdd = (client, member, sqlcon) => {54 GetLoggingStatus(sqlcon, member.guild.id, function (LogObject) {55 if (!LogObject.MemberLogging || !LogObject.MemberLoggingChannel) return;56 let mlogchannel = member.guild.channels.find((channel => channel.id === LogObject.MemberLoggingChannel));57 if (mlogchannel == null) return58 let User = client.users.find(user => user.id === member.id);59 var cdate = moment(new Date(User.createdAt));60 let Guild = member.guild;61 let ageS = moment(cdate).fromNow(true)62 let ageA = ageS.split(" ");63 const sInfo = new Discord.RichEmbed()64 .setAuthor(`${member.displayName}`)65 .setDescription(member + " **has joined the guild**")66 .setColor('#e450f4')67 .setFooter(`User ID: ${member.id}`)68 .setTimestamp()69 .setThumbnail(member.user.avatarURL)70 .addField("Total members", `${Guild.memberCount}`, true)71 .addField("Creation Date:", `${cdate.format("MMMM Do YYYY HH:mm")}\n(${moment(cdate).fromNow()})`, true);72 if (ageA[2] === "seconds" || ageA[1] === "minute" || ageA[1] === "minutes" || ageA[1] === "hour" || ageA[1] === "hours" || ageA[1] === "day" || ageA[1] === "days") {73 if (!Guild.roles.find(role => role.name === "Anti-Alt")) MakeAntiAlt(member);74 sInfo.addField("WARNING!", "This account is less than 30 days old, so has been given the Anti-Alt role")75 let Role = member.guild.roles.find(role => role.name === "Anti-Alt")76 member.addRole(Role).catch(O_o => { });77 member.send(`Thank you for joining ${member.guild.name}, but due to your account age, you have been given the Anti-Alt role which limits your permissions.`)78 }79 mlogchannel.send(sInfo)80 })81}82module.exports.MemberRemove = (client, member, sqlcon) => {83 GetLoggingStatus(sqlcon, member.guild.id, function (LogObject) {84 if (!LogObject.MemberLogging || !LogObject.MemberLoggingChannel) return;85 let logs = member.guild.fetchAuditLogs({ type: 20, limit: 1 }).catch(O_o => { });86 let mlogchannel = member.guild.channels.find((channel => channel.id === LogObject.MemberLoggingChannel));87 if (mlogchannel == null) return88 const sInfo = new Discord.RichEmbed()89 .setDescription(member + " **has left the guild**")90 .setAuthor(`${member.displayName}`)91 .setColor(member.displayHexColor)92 .setFooter(`User ID: ${member.id}`)93 .setTimestamp()94 .setThumbnail(member.user.avatarURL)95 .addField("Total members", `${member.guild.memberCount}`, true)96 mlogchannel.send(sInfo)97 if (logs.entries != undefined) {98 let entry = logs.entries.first();99 let warnchannel = member.guild.channels.find((channel => channel.id === LogObject.ModLoggingChannel));100 if (entry.createdTimestamp > (Date.now() - 5000)) {101 let Reason = entry.reason102 if (!entry.reason) Reason = "No reason given!"103 let muteEmbed = new Discord.RichEmbed()104 .setAuthor(`${member.user.tag} has been kicked`, member.user.avatarURL)105 .setColor(member.displayHexColor)106 .setFooter(`UserID: ${member.user.id}`)107 .setTimestamp()108 .setThumbnail(member.user.avatarURL)109 .addField(`Kick:`,110 `Kicked by ${entry.executor}`111 + `\n**Time of kick:** ${moment(Date.now()).format('DD MMM YYYY, HH:mm')}`112 + `\nReason: ${Reason}`);113 warnchannel.send(muteEmbed)114 }115 }116 })117}118module.exports.MemberUpdate = (client, oldMem, newMem, sqlcon) => {119 if(oldMem.nickname == newMem.nickname) return120 GetLoggingStatus(sqlcon, oldMem.guild.id, function (LogObject) {121 if (!LogObject.MemberLogging || !LogObject.MemberLoggingChannel) return;122 let mlogchannel = oldMem.guild.channels.find((channel => channel.id === LogObject.MemberLoggingChannel));123 if (mlogchannel == null) return;124 const sInfo = new Discord.RichEmbed()125 .setAuthor(`${oldMem.user.tag} - Nickname Updated`, oldMem.user.avatarURL)126 .setColor(oldMem.displayHexColor)127 .setTimestamp()128 if (oldMem.nickname === null) sInfo.addField("Old nickname", "None")129 else sInfo.addField("Old nickname", oldMem.nickname)130 if (newMem.nickname === null) sInfo.addField("New nickname", "None")131 else sInfo.addField("New nickname", newMem.nickname)132 mlogchannel.send(sInfo).catch(O_o => { });133 })134}135module.exports.AddBan = (client, member, sqlcon) => {136 GetLoggingStatus(sqlcon, member.guild.id, function (LogObject) {137 if (!LogObject.ModLogging || !LogObject.ModLoggingChannel) return;138 let logs = member.guild.fetchAuditLogs({ type: 22, limit: 1 }).catch(O_o => { });139 if (logs.entries == undefined) return140 let entry = logs.entries.first();141 let warnchannel = guild.channels.find((channel => channel.id === LogObject.ModLoggingChannel));142 if (warnchannel == undefined) return143 if (entry.createdTimestamp > (Date.now() - 5000)) {144 let Reason = entry.reason145 if (!entry.reason) Reason = "No reason given!"146 let muteEmbed = new Discord.RichEmbed()147 .setAuthor(`${user.username}#${user.discriminator} has been banned`, user.avatarURL)148 .setColor(user.displayHexColor)149 .setFooter(`UserID: ${user.id}`)150 .setTimestamp()151 .setThumbnail(user.avatarURL)152 .addField(`Ban:`,153 `Banned by ${entry.executor}`154 + `\n**Time of ban:** ${moment(Date.now()).format('DD MMM YYYY, HH:mm')}`155 + `\nReason: ${Reason}`);156 warnchannel.send(muteEmbed)157 }158 })159}160//#endregion161function GetLoggingStatus(sqlcon, ID, Callback) {162 let LogObject = new Object()163 sqlcon.query(`SELECT * FROM guildprefs WHERE GuildID = ?`, [ID], (err, logs) => {164 if (!logs || logs.length < 1) return false165 if (logs[0].MemLog == 1) LogObject.MemberLogging = true;166 else LogObject.MemberLogging = false;167 LogObject.MemberLoggingChannel = logs[0].MemLogChan;168 if (logs[0].MsgLog == 1) LogObject.MessageLogging = true;169 else LogObject.MessageLogging = false;170 LogObject.MessageLoggingChannel = logs[0].MsgLogChan;171 if (logs[0].ModLog == 1) LogObject.ModLogging = true;172 else LogObject.ModLogging = false;173 LogObject.ModLoggingChannel = logs[0].ModLogChan;174 return Callback(LogObject);175 })176}177function MakeAntiAlt(member) {178 member.guild.createRole({179 name: "Anti-Alt",180 color: `#df6968`,181 hoist: false,182 position: 9,183 permissions: [],184 mentionable: false185 }).catch(error => { return member.reply(`Sorry, i was unable to execute that command. ${error}`) });186 setTimeout(function () {187 let Guild = member.guild188 let blarg = Guild.channels.filter(channel => channel.type === "text")189 blarg.forEach(f => {190 let mrole = member.guild.roles.find(role => role.name === "Anti-Alt").id191 f.overwritePermissions(mrole, {192 ATTACH_FILES: false,193 EMBED_LINKS: false,194 ADD_REACTIONS: false,195 USE_EXTERNAL_EMOJIS: false,196 CREATE_INSTANT_INVITE: false,197 })198 });199 }, 300);...

Full Screen

Full Screen

logSystem.js

Source:logSystem.js Github

copy

Full Screen

1// Logging System2const systemglobal = require('../../config.json');3const colors = require('colors');4const { hostname } = require("os");5const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs));6const graylog2 = require("graylog2");7let logger1 = undefined8let logger2 = undefined9let remoteLogging1 = false10let remoteLogging2 = false11module.exports = function (facility, options) {12 let module = {};13 if (systemglobal.LogServer && systemglobal.LogServer.length > 0) {14 if (systemglobal.LogServer.length >= 1) {15 remoteLogging1 = true16 logger1 = new graylog2.graylog({17 servers: [systemglobal.LogServer[0]],18 hostname: hostname(),19 facility: facility,20 bufferSize: 135021 });22 logger1.on('error', (error) => { console.error('Error while trying to write to graylog host NJA:'.red, error) });23 logger1.debug(`Init : Forwarding logs to Graylog Server 1`, { process: 'Init' });24 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][Init] Forwarding logs to Graylog Server 1 - ${facility}`.gray);25 }26 if (systemglobal.LogServer.length >= 2) {27 remoteLogging2 = true28 logger2 = new graylog2.graylog({29 servers: [systemglobal.LogServer[1]],30 hostname: hostname(),31 facility: facility,32 bufferSize: 135033 });34 logger2.on('error', (error) => { console.error('Error while trying to write to graylog host END:'.red, error) });35 logger1.debug(`Init : Forwarding logs to Graylog Server 2`, { process: 'Init' });36 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][Init] Forwarding logs to Graylog Server 2 - ${facility}`.gray);37 }38 }39 module.printLine = async function printLine(proccess, text, level, object, object2) {40 let logObject = {}41 let logClient = "Unknown"42 if (proccess) {43 logClient = proccess44 }45 logObject.process = logClient46 let logString = `${logClient} : ${text}`47 if (typeof object !== 'undefined' || (object && object !== null)) {48 if ( (typeof (object) === 'string' || typeof (object) === 'number' || object instanceof String) ) {49 logString += ` : ${object}`50 } else if (typeof(object) === 'object') {51 logObject = Object.assign({}, logObject, object)52 if (object.hasOwnProperty('message')) {53 logString += ` : ${object.message}`54 } else if (object.hasOwnProperty('sqlMessage')) {55 logString += ` : ${object.sqlMessage}`56 } else if (object.hasOwnProperty('itemFileData')) {57 delete logObject.itemFileData58 logObject.itemFileData = object.itemFileData.length59 } else if (object.hasOwnProperty('itemFileArray')) {60 delete logObject.itemFileArray61 }62 }63 }64 if (typeof object2 !== 'undefined' || (object2 && object2 !== null)) {65 if (typeof(object2) === 'string' || typeof(object2) === 'number' || object2 instanceof String) {66 logObject.extraMessage = object2.toString()67 } else if (typeof(object2) === 'object') {68 logObject = Object.assign({}, logObject, object2)69 if (object2.hasOwnProperty('itemFileData')) {70 delete logObject.itemFileData71 logObject.itemFileData = object2.itemFileData.length72 } else if (object.hasOwnProperty('itemFileArray')) {73 delete logObject.itemFileArray74 }75 }76 }77 if (level === "warn" || level === "warning") {78 if (remoteLogging1) { logger1.warning(logString, logObject) }79 if (remoteLogging2) { logger2.warning(logString, logObject) }80 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.black.bgYellow)81 if (!text.toLowerCase().includes('block')) {82 console.error(logObject)83 }84 } else if (level === "error" || level === "err") {85 if (remoteLogging1) { logger1.error(logString, logObject) }86 if (remoteLogging2) { logger2.error(logString, logObject) }87 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.black.bgRed)88 console.error(logObject)89 } else if (level === "critical" || level === "crit") {90 if (remoteLogging1) { logger1.critical(logString, logObject) }91 if (remoteLogging2) { logger2.critical(logString, logObject) }92 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.bgMagenta)93 console.error(logObject)94 } else if (level === "alert") {95 if (remoteLogging1) { logger1.alert(logString, logObject) }96 if (remoteLogging2) { logger2.alert(logString, logObject) }97 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.red)98 console.log(logObject)99 } else if (level === "emergency") {100 if (remoteLogging1) { logger1.emergency(logString, logObject) }101 if (remoteLogging2) { logger2.emergency(logString, logObject) }102 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.bgMagenta)103 console.error(logObject)104 sleep(250).then(() => {105 process.exit(4);106 })107 } else if (level === "notice") {108 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.green)109 if (remoteLogging1) { logger1.notice(logString, logObject) } else { console.log(logObject) }110 if (remoteLogging2) { logger2.notice(logString, logObject) }111 } else if (level === "alert") {112 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.green)113 if (remoteLogging1) { logger1.alert(logString, logObject) } else { console.log(logObject) }114 if (remoteLogging2) { logger2.alert(logString, logObject) }115 } else if (level === "debug") {116 if (remoteLogging1) { logger1.debug(logString, logObject) } else { console.log(logObject) }117 if (remoteLogging2) { logger2.debug(logString, logObject) }118 if (text.includes("New Message: ") || text.includes("Reaction Added: ")) {119 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.black.bgCyan)120 } else if (text.includes('Message Deleted: ') || text.includes('Reaction Removed: ')) {121 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.black.bgBlue)122 } else if (text.includes('Send Message: ') || text.includes('Status Update: ')) {123 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.black.bgGreen)124 } else if (text.includes('Send Package: ')) {125 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.black.bgCyan)126 } else {127 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.gray)128 }129 } else if (level === "info") {130 if (remoteLogging1) { logger1.info(logString, logObject) } else { console.log(logObject) }131 if (remoteLogging2) { logger2.info(logString, logObject) }132 if (text.includes("Sent message to ") || text.includes("Connected to Kanmi Exchange as ")) {133 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.gray)134 } else if (text.includes('New Media Tweet in')) {135 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.black.bgGreen)136 } else if (text.includes('New Text Tweet in')) {137 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.black.bgGreen)138 } else {139 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`.blue)140 }141 } else {142 if (remoteLogging1) { logger1.error(logString, logObject) } else { console.log(logObject) }143 if (remoteLogging2) { logger2.error(logString, logObject) }144 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][${proccess}] ${text}`)145 }146 }147 process.on('uncaughtException', function(err) {148 console.log(err)149 console.log(`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}][uncaughtException] ${err.message}`.bgRed);150 if (remoteLogging1) { logger1.critical(`uncaughtException : ${err.message}`, { process: 'Init' }); }151 if (remoteLogging2) { logger2.critical(`uncaughtException : ${err.message}`, { process: 'Init' }); }152 });153 return module;...

Full Screen

Full Screen

system-logger.js

Source:system-logger.js Github

copy

Full Screen

1const fileManager = require('./file-manager');2const consoleManager = require('./console-manager');3const definitions = require('./definitions');4let configurations = {5 logLevelFile: definitions.LOG_LEVEL_DEBUG,6 logLevelConsole: definitions.LOG_LEVEL_INFO,7 logLevelCallback: definitions.LOG_LEVEL_DEBUG,8 developmentMode: false,9 timezone: definitions.DEFAULT_TIMEZONE,10 moduleName: definitions.DEFAULT_MODULE_NAME,11 maximumLogFieSize: definitions.NO_MAX_LOG_SIZE,12 callbackLogEvent: null,13 callbackLogSwitch: null,14 logDirectory: '.',15 customBannerHeaders: definitions.DEFAULT_CUSTOM_BANNER16};17let registeredAliases = {18 'debug' : { code: 'DEBUG', level: definitions.LOG_LEVEL_DEBUG, color: 'DEFAULT' },19 'info' : { code: 'INFO', level: definitions.LOG_LEVEL_INFO, color: 'DEFAULT' },20 'warn' : { code: 'WARN', level: definitions.LOG_LEVEL_WARNING, color: 'YELLOW' },21 'crit' : { code: 'CRIT', level: definitions.LOG_LEVEL_CRITICAL, color: 'RED' }22};23//*************************************************************************************************24function getTime() {25 let now = new Date(new Date().toLocaleString('en-US', { timeZone:configurations.timezone }));26 return ('0' + now.getHours()).substr(-2,2) + ':' +27 ('0' + now.getMinutes()).substr(-2,2) + ':' +28 ('0' + now.getSeconds()).substr(-2,2);29}30//*************************************************************************************************31function getDate() {32 let now = new Date(new Date().toLocaleString('en-US', { timeZone: configurations.timezone }));33 return now.getFullYear() + '/' +34 ('0' + (now.getMonth() + 1)).substr(-2,2) + '/' +35 ('0' + now.getDate()).substr(-2,2);36}37//*************************************************************************************************38function sendToConsole(logObject) {39 if (configurations.logLevelConsole < 0) {40 return;41 }42 if (logObject.logLevel < configurations.logLevelConsole) {43 return;44 }45 let logMessage = `${logObject.date} | ${logObject.time} | ${logObject.code} | ${logObject.message}`;46 consoleManager.write(logMessage, logObject.color);47}48//*************************************************************************************************49function sendToFile(logObject) {50 if (configurations.logLevelFile < 0) {51 return;52 }53 if (logObject.logLevel < configurations.logLevelFile) {54 return;55 }56 let logMessage = `${logObject.date} | ${logObject.time} | ${logObject.code} | ${logObject.message}`;57 fileManager.write(logMessage);58 if (logObject.object === null) {59 return;60 }61 let objectStr = logObject.object;62 if (typeof(logObject.object) !== 'string'){63 objectStr = JSON.stringify(logObject.object, null, 4);64 }65 const uniqueIdentifier = Math.random().toString(36).substring(2, 4).toUpperCase();66 for (const line of objectStr.split('\n')) {67 fileManager.write(`[${uniqueIdentifier}]~ ${line}`);68 }69}70//*************************************************************************************************71function sendToCallback(logObject) {72 if (configurations.logLevelCallback < 0) {73 return;74 }75 if (logObject.logLevel < configurations.logLevelCallback) {76 return;77 }78 if (configurations.callbackLogEvent !== null) {79 configurations.callbackLogEvent(logObject);80 }81}82//*************************************************************************************************83function handleLogMessage(alias, message, object = null) {84 if (!(alias in registeredAliases)) {85 throw new Error(`Unregistered alias[${alias}] used.`);86 }87 const aliasConfig = registeredAliases[alias];88 const logObject = {89 alias: alias,90 message: message,91 code: aliasConfig.code,92 color: aliasConfig.color,93 logLevel: aliasConfig.level,94 time: getTime(),95 date: getDate(),96 object: object97 };98 sendToConsole(logObject);99 sendToFile(logObject);100 sendToCallback(logObject);101}102//*************************************************************************************************103exports.initialize = function(moduleName, userOptions = {}) {104 configurations = Object.assign(configurations, userOptions);105 configurations.moduleName = moduleName;106 if (configurations.logLevelFile > definitions.LOG_LEVEL_DISABLED) {107 fileManager.init(configurations.moduleName, {108 customBannerHeaders: configurations.customBannerHeaders,109 devMode: configurations.developmentMode,110 timezone: configurations.timezone,111 logSwitchSize: configurations.maximumLogFieSize,112 callbackLogSwitch: configurations.callbackLogSwitch,113 logLevel: configurations.logLevelFile,114 logDirectory: configurations.logDirectory115 })116 }117};118//*************************************************************************************************119exports.debug = function(message, object = null) {120 handleLogMessage('debug', message, object)121};122//*************************************************************************************************123exports.info = function(message, object = null) {124 handleLogMessage('info', message, object)125};126//*************************************************************************************************127exports.warn = function(message, object = null) {128 handleLogMessage('warn', message, object)129};130//*************************************************************************************************131exports.crit = function(message, object = null) {132 handleLogMessage('crit', message, object)133};134//*************************************************************************************************135exports.addStatusCode = function (alias, code, level, color = 'DEFAULT') {136 if (!String(color).toUpperCase() in Object.keys(definitions.CONSOLE_COLORS)) {137 throw Error(`'${color}' is not a valid color preference`);138 }139 registeredAliases[alias] = {140 code: code,141 level: level,142 color: color143 };144 145 exports[alias] = function (message, object = null) {146 handleLogMessage(alias, message, object)147 }...

Full Screen

Full Screen

Logger.js

Source:Logger.js Github

copy

Full Screen

1const si = require("systeminformation");2const iplocation = require("iplocation").default;3const geohash = require("ngeohash");4const _ = require("lodash");5const multilog = require("../multilogger");6let logObject = {};7let dbMetricsObject = {};8let perfMetricsObject = {};9// Creates a log object10const log = (extended, development) => {11 return async (req, res, next) => {12 const startHrTime = process.hrtime();13 res.on("finish", async () => {14 const elapsedHrTime = process.hrtime(startHrTime);15 const elapsedTimeInMs = elapsedHrTime[0] * 1000 + elapsedHrTime[1] / 1e6;16 const realBody = _.isEmpty(req.body) ? " " : JSON.stringify(req.body);17 const cpuUsage = await getCpuInfo();18 const memoryUsage = await getMemInfo();19 const hostInfo = await getHostInfo();20 const location = await iplocation(req.connection.remoteAddress)21 .then(result => {22 result.geohash = geohash.encode(result.latitude, result.longitude);23 return result;24 })25 .catch(err => {});26 if (extended) {27 getBasic(req, res, hostInfo, elapsedTimeInMs);28 getParameters(req, realBody);29 getAuth(req);30 getPerformance(cpuUsage, memoryUsage);31 }32 logObject.method = req.method || " ";33 logObject.statusCode = res.statusCode || " ";34 logObject.statusMessage = res.statusMessage || " ";35 logObject.date = new Date().toUTCString();36 logObject.responseTime = elapsedTimeInMs;37 logObject.contentType = req.header("Content-Type") || " ";38 logObject.hostname = req.hostname || " ";39 logObject.osHost = hostInfo.hostname || " ";40 logObject.url = req.originalUrl || req.url || " ";41 logObject.path =42 res.statusCode !== 404 && req.route && req.route.path43 ? req.route.path44 : " ";45 logObject.body = req.method === "POST" ? realBody : " ";46 logObject.params = _.isEmpty(req.params)47 ? " "48 : JSON.stringify(req.params);49 logObject.query = _.isEmpty(req.query) ? " " : JSON.stringify(req.query);50 logObject.cookies = _.isEmpty(req.cookies)51 ? " "52 : JSON.stringify(req.cookies);53 logObject.auth =54 req.header("Authorization") || req.header("x-access-token") || " ";55 logObject.ip = req.connection.remoteAddress || req.ip || " ";56 logObject.location = location || " ";57 logObject.clientInfo = req.header("User-Agent") || " ";58 logObject.errorMessage = res.locals.multiError || " ";59 if (development) {60 console.log(logObject);61 }62 multilog.pushToData(logObject);63 logObject = {};64 });65 next();66 };67};68const addToDbMetricsObject = ({ name, timing, ...custom } = {}) => {69 dbMetricsObject = {70 name,71 timing72 };73 _.flatMap(custom, param => {74 return _.map(param, (value, key) => {75 return (dbMetricsObject[key] = value);76 });77 });78 multilog.pushToDatabaseMetrics(dbMetricsObject);79 dbMetricsObject = {};80};81const addToPerformanceObject = async () => {82 perfMetricsObject = {83 memoryUsage: await getMemInfo(),84 cpuUsage: await getCpuInfo(),85 osHost: await getHostInfo(),86 };87 await multilog.pushToPerformanceMetrics(perfMetricsObject);88 perfMetricsObject = {};89};90const getBasic = (req, res, hostinfo, elapsed) => {91 console.log("\n=====- Multilogger v1.0.11 -=====");92 console.log("--- Basic ---\n");93 console.info(94 `${req.method} ––– ${res.statusCode} ––– ${95 res.statusMessage96 } at ${new Date().toLocaleString()}`97 );98 console.info(`Response-time: ${elapsed}`);99 console.info(100 `Content Type: ${req.header("Content-Type") || "No content type given"}`101 );102 console.info(`Hostname: ${req.hostname}`);103 console.info(`OS hostname: ${hostinfo.hostname}`);104 console.info(105 `Path & URL: ${(req.route && req.route.path) ||106 "No Path"} ––– ${req.originalUrl || req.url || "No Url"}`107 );108};109const getParameters = (req, realBody) => {110 console.log("\n--- Parameters ---\n");111 if (realBody) {112 console.info(`Request body: ${realBody}`);113 } else {114 console.info(`Request body: Body was empty`);115 }116 if (req.params && Object.keys(req.params).length !== 0) {117 console.info(`Parameters: ${JSON.stringify(req.params)}`);118 } else {119 console.info("Parameters: No parameters given");120 }121 if (req.query && Object.keys(req.query).length !== 0) {122 console.info(`Query: ${JSON.stringify(req.query)}`);123 } else {124 console.info("Query: No query given ❓");125 }126 console.info(127 `Cookies & Storage: ${JSON.stringify(req.cookies) || "No tasty cookies 🍪"}`128 );129};130const getAuth = req => {131 console.log("\n--- Authorization ---\n");132 console.info(133 `Authorization: ${req.header("Authorization") ||134 req.header("x-access-token") ||135 "No authorization tokens ⛔"}`136 );137 console.info(138 `Client: ${req.connection.remoteAddress ||139 req.ip ||140 "No IP found"} ––– ${req.header("User-Agent")}`141 );142};143const getPerformance = (cpuInfo, memoryInfo) => {144 console.log("\n--- Performance ---\n");145 console.info(`Memory Usage: ${JSON.stringify(memoryInfo)}`);146 console.info(`CPU Usage: ${JSON.stringify(cpuInfo)}`);147};148// GET CPU INFO149const getCpuInfo = () => {150 return si.currentLoad();151};152// GET MEMORY INFO153const getMemInfo = async () => {154 const mem = await si.mem();155 return {156 free: mem.free,157 used: mem.active,158 total: (mem.total / Math.pow(1024, 3)).toFixed(2)159 };160};161// GET HOST INFO162const getHostInfo = () => {163 return si.osInfo();164};165module.exports = {166 log,167 addToDbMetricsObject,168 addToPerformanceObject,...

Full Screen

Full Screen

LOG.js

Source:LOG.js Github

copy

Full Screen

1/*class LOG2{3 constructor(x,y,width,height,angle)4 {5 var option=6 {7 'restitution':0.8,8 'friction':1.0,9 'density':1.010 }11 this.logobject=Bodies.rectangle(x,y,width,height,option);12 Matter.Body.setAngle(this.logobject,angle);13 World.add(world,this.logobject);14 this.width=width;15 this.height=height;16 17 1819 20 }21display()22{23 var angle=this.logobject.angle;24 push();25 26 translate(this.logobject.position.x,this.logobject.position.y);27 28 rotate(angle);29 30 rect(0,0,this.width,this.height);3132 pop();33}34}*/3536class Log { constructor(x,y,height,angle) 37 { var options={ 'restitution':0.8, 'friction':1.0, 'density':1.0 } 38 this.logObject=Bodies.rectangle(x,y,20,height,options); 39 this.width=20; 40 this.height=height; 41 Matter.Body.setAngle( this.logObject,angle); 42 World.add(world,this.logObject); } 43 display() 44 { push(); 45 translate(this.logObject.position.x,this.logObject.position.y) 46 rotate(this.logObject.angle);47 fill("white"); 48 stroke("orange"); 49 strokeWeight(4); 50 rectMode(CENTER);51 rect(0,0,this.width,this.height); 52 pop(); } }5354 ...

Full Screen

Full Screen

log.service.js

Source:log.service.js Github

copy

Full Screen

1let LogService = class LogService {2 debug(logObject) {3 abp.log.debug(logObject);4 }5 info(logObject) {6 abp.log.info(logObject);7 }8 warn(logObject) {9 abp.log.warn(logObject);10 }11 error(logObject) {12 abp.log.error(logObject);13 }14 fatal(logObject) {15 abp.log.fatal(logObject);16 }17};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 'Demo test Google' : function (browser) {3 .waitForElementVisible('body', 1000)4 .setValue('input[type=text]', 'nightwatch')5 .waitForElementVisible('button[name=btnG]', 1000)6 .click('button[name=btnG]')7 .pause(1000)8 .assert.containsText('#main', 'Night Watch')9 .end();10 }11};

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 'Demo test Google' : function (browser) {3 .waitForElementVisible('body', 1000)4 .setValue('input[type=text]', 'nightwatch')5 .waitForElementVisible('button[name=btnG]', 1000)6 .click('button[name=btnG]')7 .pause(1000)8 .assert.containsText('#main', 'Night Watch')9 .end();10 }11};

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 'Demo test' : function (browser) {3 .waitForElementVisible('body', 1000)4 .setValue('input[type=text]', 'nightwatch')5 .waitForElementVisible('button[name=btnG]', 1000)6 .click('button[name=btnG]')7 .pause(1000)8 .assert.containsText('#main', 'Night Watch')9 .end();10 }11};

Full Screen

Using AI Code Generation

copy

Full Screen

1this.logObject(testObject);2this.logObject(testObject, 'Test Object');3this.logObject(testObject, 'Test Object', 'info');4this.logObject(testObject, 'Test Object', 'info', true);5this.logObject(testObject, 'Test Object', 'info', true, true);6this.logObject(testObject, 'Test Object', 'info', true, true, true);7this.logObject(testObject, 'Test Object', 'info', true, true, true, true);8this.logObject(testObject, 'Test Object', 'info', true, true, true, true, true);9this.logObject(testObject, 'Test Object', 'info', true, true, true, true, true, true);10this.logObject(testObject, 'Test Object', 'info', true, true, true, true, true, true, true);11this.logObject(testObject, 'Test Object', 'info', true, true, true, true, true, true, true, true);12this.logObject(testObject, 'Test Object', 'info', true, true, true, true, true, true, true, true, true);13this.logObject(testObject, 'Test Object', 'info', true, true, true, true, true, true, true, true, true, true);

Full Screen

Using AI Code Generation

copy

Full Screen

1var logger = require('nightwatch/lib/util/logger.js');2logger.logObject({3});4{ a: 1, b: 2, c: 3 }5var logger = require('nightwatch/lib/util/logger.js');6logger.logError({7});8{ a: 1, b: 2, c: 3 }9var logger = require('nightwatch/lib/util/logger.js');10logger.logAssertion({11});12{ a: 1, b: 2, c: 3 }13var logger = require('nightwatch/lib/util/logger.js');14logger.logScreenshot({15});16{ a: 1, b: 2, c: 3 }17var logger = require('nightwatch/lib/util/logger.js');18logger.logSession({19});20{ a: 1, b: 2, c: 3 }21var logger = require('nightwatch/lib/util/logger.js');22logger.logResults({23});24{ a: 1, b: 2, c: 3 }25var logger = require('nightwatch/lib/util/logger.js');26logger.logTestcase({27});28{ a: 1, b: 2, c: 3 }

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 'test': function (client) {3 client.logObject('someObject', { some: 'object' });4 }5};6module.exports = {7 'test': function (client) {8 client.logElements('someObject', { some: 'object' });9 }10};11module.exports = {12 'test': function (client) {13 client.logElement('someObject', { some: 'object' });14 }15};16module.exports = {17 'test': function (client) {18 client.logElementArray('someObject', { some: 'object' });19 }20};21module.exports = {22 'test': function (client) {23 client.logElementArray('someObject', { some: 'object' });24 }25};26module.exports = {27 'test': function (client) {28 client.logElementArray('someObject', { some: 'object' });29 }30};31module.exports = {32 'test': function (client) {33 client.logElementArray('someObject', { some: 'object' });34 }35};36module.exports = {37 'test': function (client) {38 client.logElementArray('someObject', { some: 'object' });39 }40};41module.exports = {42 'test': function (client) {43 client.logElementArray('someObject', { some: '

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 'Test Case' : function (client) {3 .logObject('Test Case')4 .end();5 }6};

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Nightwatch automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful