How to use requestEndLoggingFormat method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

helpers.js

Source:helpers.js Github

copy

Full Screen

1"use strict";2var _ = require("underscore")3 , gridRegister = require('./grid-register.js')4 , logger = require('./logger.js').get('appium')5 , status = require('./status.js')6 , io = require('socket.io')7 , mkdirp = require('mkdirp')8 , bytes = require('bytes')9 , domain = require('domain')10 , format = require('util').format11 , Args = require("vargs").Constructor;12module.exports.allowCrossDomain = function (req, res, next) {13 safely(req, function () {14 res.header('Access-Control-Allow-Origin', '*');15 res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,OPTIONS,DELETE');16 res.header('Access-Control-Allow-Headers', 'origin, content-type, accept');17 });18 // need to respond 200 to OPTIONS19 if ('OPTIONS' === req.method) {20 safely(req, function () {21 res.sendStatus(200);22 });23 } else {24 next();25 }26};27module.exports.winstonStream = {28 write: function (msg) {29 msg = msg.replace(/$\s*$/m, "");30 msg = msg.replace(/\[[^\]]+\] /, "");31 logger.log('debug', msg);32 }33};34module.exports.catchAllHandler = function (e, req, res, next) {35 safely(req, function () {36 res.status(500).send({37 status: status.codes.UnknownError.code38 , value: "ERROR running Appium command: " + e.message39 });40 });41 next(e);42};43module.exports.checkArgs = function (parser, args) {44 var exclusives = [45 ['noReset', 'fullReset']46 , ['ipa', 'safari']47 , ['app', 'safari']48 , ['forceIphone', 'forceIpad']49 , ['deviceName', 'defaultDevice']50 ];51 _.each(exclusives, function (exSet) {52 var numFoundInArgs = 0;53 _.each(exSet, function (opt) {54 if (_.has(args, opt) && args[opt]) {55 numFoundInArgs++;56 }57 });58 if (numFoundInArgs > 1) {59 console.error(("You can't pass in more than one argument from the set " +60 JSON.stringify(exSet) + ", since they are mutually exclusive").red);61 process.exit(1);62 }63 });64 var checkValidPort = function (port) {65 if (port > 0 && port < 65536) return true;66 console.error("Port must be greater than 0 and less than 65536");67 return false;68 };69 var validations = {70 port: checkValidPort71 , callbackPort: checkValidPort72 , bootstrapPort: checkValidPort73 , selendroidPort: checkValidPort74 , chromedriverPort: checkValidPort75 , robotPort: checkValidPort76 , backendRetries: function (r) { return r >= 0; }77 };78 var nonDefaultArgs = getNonDefaultArgs(parser, args);79 _.each(validations, function (validator, arg) {80 if (_.has(nonDefaultArgs, arg)) {81 if (!validator(args[arg])) {82 console.error("Invalid argument for param " + arg + ": " + args[arg]);83 process.exit(1);84 }85 }86 });87};88module.exports.noColorLogger = function (tokens, req, res) {89 var len = parseInt(res.getHeader('Content-Length'), 10);90 len = isNaN(len) ? '' : ' - ' + bytes(len);91 return req.method + ' ' + req.originalUrl + ' ' +92 res.statusCode + ' ' + (new Date() - req._startTime) + 'ms' + len;93};94module.exports.configureServer = function (rawConfig, appiumVer, appiumServer,95 cb) {96 var appiumRev;97 if (!rawConfig) {98 return cb(new Error('config data required'));99 }100 var versionMismatches = {};101 var excludedKeys = ["git-sha", "node_bin", "built"];102 _.each(rawConfig, function (deviceConfig, key) {103 if (deviceConfig.version !== appiumVer && !_.contains(excludedKeys, key)) {104 versionMismatches[key] = deviceConfig.version;105 } else if (key === "git-sha") {106 appiumRev = rawConfig['git-sha'];107 }108 });109 if (_.keys(versionMismatches).length) {110 logger.error("Got some configuration version mismatches. Appium is " +111 "at " + appiumVer + ".");112 _.each(versionMismatches, function (mismatchedVer, key) {113 logger.error(key + " configured at " + mismatchedVer);114 });115 logger.error("Please re-run reset.sh or config");116 return cb(new Error("Appium / config version mismatch"));117 } else {118 appiumServer.registerConfig(rawConfig);119 cb(null, appiumRev);120 }121};122module.exports.conditionallyPreLaunch = function (args, appiumServer, cb) {123 if (args.launch) {124 logger.debug("Starting Appium in pre-launch mode");125 appiumServer.preLaunch(function (err) {126 if (err) {127 logger.error("Could not pre-launch appium: " + err);128 cb(err);129 } else {130 cb(null);131 }132 });133 } else {134 cb(null);135 }136};137module.exports.prepareTmpDir = function (args, cb) {138 if (args.tmpDir === null) return cb();139 mkdirp(args.tmpDir, function (err) {140 if (err) {141 logger.error("Could not ensure tmp dir '" + args.tmpDir + "' exists");142 logger.error(err);143 }144 cb(err);145 });146};147var startAlertSocket = function (restServer, appiumServer) {148 var alerts = io(restServer, {149 'flash policy port': -1,150 'logger': logger,151 'log level': 1,152 'polling duration': 10,153 'transports': ['websocket', 'flashsocket']154 });155 alerts.sockets.on("connection", function (socket) {156 logger.debug("Client connected: " + (socket.id).toString());157 socket.on('disconnect', function (data) {158 logger.debug("Client disconnected: " + data);159 });160 });161 // add web socket so we can emit events162 appiumServer.attachSocket(alerts);163};164var getNonDefaultArgs = function (parser, args) {165 var nonDefaults = {};166 _.each(parser.rawArgs, function (rawArg) {167 var arg = rawArg[1].dest;168 if (args[arg] !== rawArg[1].defaultValue) {169 nonDefaults[arg] = args[arg];170 }171 });172 return nonDefaults;173};174var getDeprecatedArgs = function (parser, args) {175 var deprecated = {};176 _.each(parser.rawArgs, function (rawArg) {177 var arg = rawArg[1].dest;178 if (args[arg] && rawArg[1].deprecatedFor) {179 deprecated[rawArg[0]] = "use instead: " + rawArg[1].deprecatedFor;180 }181 });182 return deprecated;183};184module.exports.startListening = function (server, args, parser, appiumVer, appiumRev, appiumServer, cb) {185 var alreadyReturned = false;186 server.listen(args.port, args.address, function () {187 var welcome = "Welcome to Appium v" + appiumVer;188 if (appiumRev) {189 welcome += " (REV " + appiumRev + ")";190 }191 logger.info(welcome);192 var logMessage = "Appium REST http interface listener started on " +193 args.address + ":" + args.port;194 logger.info(logMessage);195 startAlertSocket(server, appiumServer);196 if (args.nodeconfig !== null) {197 gridRegister.registerNode(args.nodeconfig, args.address, args.port);198 }199 var showArgs = getNonDefaultArgs(parser, args);200 if (_.size(showArgs)) {201 logger.debug("Non-default server args: " + JSON.stringify(showArgs));202 }203 var deprecatedArgs = getDeprecatedArgs(parser, args);204 if (_.size(deprecatedArgs)) {205 logger.warn("Deprecated server args: " + JSON.stringify(deprecatedArgs));206 }207 logger.info('Console LogLevel: ' + logger.transports.console.level);208 if (logger.transports.file) {209 logger.info('File LogLevel: ' + logger.transports.file.level);210 }211 });212 server.on('error', function (err) {213 if (err.code === 'EADDRNOTAVAIL') {214 logger.error("Couldn't start Appium REST http interface listener. Requested address is not available.");215 } else {216 logger.error("Couldn't start Appium REST http interface listener. Requested port is already in use. Please make sure there's no other instance of Appium running already.");217 }218 if (!alreadyReturned) {219 alreadyReturned = true;220 cb(err);221 }222 });223 server.on('connection', function (socket) {224 socket.setTimeout(600 * 1000); // 10 minute timeout225 });226 setTimeout(function () {227 if (!alreadyReturned) {228 alreadyReturned = true;229 cb(null);230 }231 }, 1000);232};233// Copied the morgan compile function over so that cooler formats234// may be configured235function compile(fmt) {236 fmt = fmt.replace(/"/g, '\\"');237 var js = ' return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g,238 function (_, name, arg) {239 return '"\n + (tokens["' + name + '"](req, res, "' + arg + '") || "-") + "';240 }) + '";';241 // jshint evil:true242 return new Function('tokens, req, res', js);243}244module.exports.requestStartLoggingFormat = compile('-->'.white + ' ' + ':method'.white + ' ' +245 ':url'.white);246// Copied the morgan format.dev function, modified to use colors package247// and custom logging line248module.exports.requestEndLoggingFormat = function (tokens, req, res) {249 var status = res.statusCode;250 var statusStr = ':status';251 if (status >= 500) statusStr = statusStr.red;252 else if (status >= 400) statusStr = statusStr.yellow;253 else if (status >= 300) statusStr = statusStr.cyan;254 else statusStr = statusStr.green;255 var fn = compile('<-- :method :url '.white + statusStr +256 ' :response-time ms - :res[content-length]'.grey);257 return fn(tokens, req, res);258};259function getRequestContext(req) {260 if (!req) return '';261 var data = '';262 try {263 if (req.body) data = JSON.stringify(req.body).substring(0, 200);264 } catch (ign) {}265 return format('context: [%s %s %s]', req.method, req.url, data).replace(/ ]$/, '');266}267// Mainly used to wrap http response methods, or for cases where errors268// perdure the domain269var safely = function () {270 var args = new (Args)(arguments);271 var req = args.all[0];272 var fn = args.callback;273 try {274 fn();275 } catch (err) {276 logger.error('Unexpected error:', err.stack, getRequestContext(req));277 }278};279module.exports.safely = safely;280module.exports.domainMiddleware = function () {281 return function (req, res, next) {282 var reqDomain = domain.create();283 reqDomain.add(req);284 reqDomain.add(res);285 res.on('close', function () {286 setTimeout(function () {287 reqDomain.dispose();288 }, 5000);289 });290 reqDomain.on('error', function (err) {291 logger.error('Unhandled error:', err.stack, getRequestContext(req));292 });293 reqDomain.run(next);294 };...

Full Screen

Full Screen

main.js

Source:main.js Github

copy

Full Screen

...78 , server = http.createServer(rest);79 rest.use(domainMiddleware());80 rest.use(morgan(function (tokens, req, res) {81 // morgan output is redirected straight to winston82 logger.info(requestEndLoggingFormat(tokens, req, res),83 (res.jsonResp || '').grey);84 }));85 rest.use(favicon(path.join(__dirname, 'static/favicon.ico')));86 rest.use(express.static(path.join(__dirname, 'static')));87 rest.use(allowCrossDomain);88 rest.use(parserWrap);89 rest.use(bodyParser.urlencoded({extended: true}));90 rest.use(bodyParser.json({limit: '50mb'}));91 rest.use(morgan({format: function (tokens, req, res) {92 // morgan output is redirected straight to winston93 var data = '';94 try {95 if (req.body) data = JSON.stringify(req.body).substring(0, 1000);96 } catch (ign) {}...

Full Screen

Full Screen

express-logging.js

Source:express-logging.js Github

copy

Full Screen

...29 let fn = compile(`${'<-- :method :url '.white}${statusStr} ${':response-time ms - :res[content-length]'.grey}`);30 return fn(tokens, req, res);31}32const endLogFormatter = morgan((tokens, req, res) => {33 log.info(requestEndLoggingFormat(tokens, req, res),34 (res.jsonResp || '').grey);35});36const requestStartLoggingFormat = compile(`${'-->'.white} ${':method'.white} ${':url'.white}`);37const startLogFormatter = morgan((tokens, req, res) => {38 // morgan output is redirected straight to winston39 let data = '';40 try {41 if (req.body) {42 data = JSON.stringify(req.body).substring(0, 1000);43 }44 } catch (ign) {}45 log.info(requestStartLoggingFormat(tokens, req, res), data.grey);46}, {immediate: true});47export { endLogFormatter, startLogFormatter };

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const requestEndLoggingFormat = require('appium-base-driver').requestEndLoggingFormat;2const requestStartLoggingFormat = require('appium-base-driver').requestStartLoggingFormat;3const responseLoggingFormat = require('appium-base-driver').responseLoggingFormat;4const responseErrorLoggingFormat = require('appium-base-driver').responseErrorLoggingFormat;5const requestErrorLoggingFormat = require('appium-base-driver').requestErrorLoggingFormat;6const logRequest = require('appium-base-driver').logRequest;7const logResponse = require('appium-base-driver').logResponse;8const logRequestError = require('appium-base-driver').logRequestError;9const logResponseError = require('appium-base-driver').logResponseError;10const logStart = require('appium-base-driver').logStart;11const logEnd = require('appium-base-driver').logEnd;12const logError = require('appium-base-driver').logError;13const logInfo = require('appium-base-driver').logInfo;14const logWarn = require('appium-base-driver').logWarn;15const logDebug = require('appium-base-driver').logDebug;16const logTrace = require('appium-base-driver').logTrace;17const logHttp = require('appium-base-driver').logHttp

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2driver.init({3}).then(function() {4}).then(function() {5 return driver.quit();6});7import { BaseDriver, errors } from 'appium-base-driver';8import _ from 'lodash';9import logger from './logger';10import { JWProxy } from 'appium-base-driver';11import { util } from 'appium-support';12import { requestEndLoggingFormat } from 'appium-base-driver/lib/basedriver/driver';13export default class AndroidDriver extends BaseDriver {14 constructor(opts = {}, shouldValidateCaps = true) {15 super(opts, shouldValidateCaps);16 this.desiredCapConstraints = {17 platformName: {18 },19 deviceName: {20 },21 app: {22 }23 };24 }25 async createSession(caps) {26 let [sessionId] = await super.createSession(caps);27 this.jwproxy = new JWProxy({server: this.opts.address, port: this.opts.port, base: ''});28 await this.jwproxy.command('/session', 'POST', {desiredCapabilities: caps});29 return [sessionId, caps];30 }31 async deleteSession() {32 await super.deleteSession();33 await this.jwproxy.command('/session', 'DELETE', {});34 }35 async get(url) {36 await this.jwproxy.command('/url', 'POST', {url});37 }38}39import _ from 'lodash';40import util from 'util';41import { requestEndLoggingFormat } from 'appium-base-driver/lib/basedriver/driver';42export default class Logger {43 constructor(prefix, logObj = {}) {44 this.prefix = prefix;45 this.logs = logObj;

Full Screen

Using AI Code Generation

copy

Full Screen

1const { AppiumBaseDriver } = require('appium-base-driver');2const { AppiumServer } = require('appium');3let appiumServer = new AppiumServer();4let appiumBaseDriver = new AppiumBaseDriver(appiumServer);5appiumBaseDriver.requestEndLoggingFormat('json');6appiumBaseDriver.requestEndLoggingFormat('junit');7appiumBaseDriver.requestEndLoggingFormat('teamcity');8appiumBaseDriver.requestEndLoggingFormat('dot');9appiumBaseDriver.requestEndLoggingFormat('spec');10appiumBaseDriver.requestEndLoggingFormat('progress');11appiumBaseDriver.requestEndLoggingFormat('nyan');12appiumBaseDriver.requestEndLoggingFormat('xunit');13appiumBaseDriver.requestEndLoggingFormat('xunit-file');14appiumBaseDriver.requestEndLoggingFormat('markdown');15appiumBaseDriver.requestEndLoggingFormat('html');16appiumBaseDriver.requestEndLoggingFormat('json-stream');17appiumBaseDriver.requestEndLoggingFormat('list');18appiumBaseDriver.requestEndLoggingFormat('tap');19appiumBaseDriver.requestEndLoggingFormat('landing');20appiumBaseDriver.requestEndLoggingFormat('min');21appiumBaseDriver.requestEndLoggingFormat('doc');22appiumBaseDriver.requestEndLoggingFormat('json-stream');23const { AppiumBaseDriver } = require('appium-base-driver');24const { AppiumServer } = require('appium');25let appiumServer = new AppiumServer();26let appiumBaseDriver = new AppiumBaseDriver(appiumServer);27appiumBaseDriver.requestStartLoggingFormat('json');28appiumBaseDriver.requestStartLoggingFormat('junit');29appiumBaseDriver.requestStartLoggingFormat('teamcity');30appiumBaseDriver.requestStartLoggingFormat('dot');31appiumBaseDriver.requestStartLoggingFormat('spec');32appiumBaseDriver.requestStartLoggingFormat('progress');33appiumBaseDriver.requestStartLoggingFormat('nyan');34appiumBaseDriver.requestStartLoggingFormat('xunit');35appiumBaseDriver.requestStartLoggingFormat('xunit-file');36appiumBaseDriver.requestStartLoggingFormat('markdown');37appiumBaseDriver.requestStartLoggingFormat('html');38appiumBaseDriver.requestStartLoggingFormat('json-stream');39appiumBaseDriver.requestStartLoggingFormat('list');40appiumBaseDriver.requestStartLoggingFormat('tap');

Full Screen

Using AI Code Generation

copy

Full Screen

1let requestEndLoggingFormat = require('appium-base-driver').requestEndLoggingFormat;2let request = {method: 'POST', url: '/wd/hub/session/1234567890/element', body: {using: 'id', value: 'test'}};3let response = {status: 200, body: {status: 0, value: {ELEMENT: '1234567890'}}};4let res = requestEndLoggingFormat(request, response);5console.log(res);6{"using":"id","value":"test"}7{"status":0,"value":{"ELEMENT":"1234567890"}}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { requestEndLoggingFormat } = require('appium-base-driver');2const { BaseDriver } = require('appium-base-driver');3class MyDriver extends BaseDriver {4 async createSession () {5 }6}7const myDriver = new MyDriver();8myDriver.requestEndLoggingFormat();9const { requestEndLoggingFormat } = require('appium-base-driver');10const { BaseDriver } = require('appium-base-driver');11class MyDriver extends BaseDriver {12 async createSession () {13 }14}15const myDriver = new MyDriver();16myDriver.requestEndLoggingFormat();17const { requestEndLoggingFormat } = require('appium-base-driver');18const { BaseDriver } = require('appium-base-driver');19class MyDriver extends BaseDriver {20 async createSession () {21 }22}23const myDriver = new MyDriver();24myDriver.requestEndLoggingFormat();25const { requestEndLoggingFormat } = require('appium-base-driver');26const { BaseDriver } = require('appium-base-driver');27class MyDriver extends BaseDriver {28 async createSession () {29 }30}31const myDriver = new MyDriver();32myDriver.requestEndLoggingFormat();33const { requestEndLoggingFormat } = require('appium-base-driver');34const { BaseDriver } = require('appium-base-driver');35class MyDriver extends BaseDriver {36 async createSession () {37 }38}39const myDriver = new MyDriver();40myDriver.requestEndLoggingFormat();41const { requestEndLoggingFormat } = require('appium-base-driver');42const { BaseDriver } = require('appium-base-driver');43class MyDriver extends BaseDriver {44 async createSession () {45 }46}47const myDriver = new MyDriver();48myDriver.requestEndLoggingFormat();49const { requestEndLoggingFormat } = require('appium-base-driver');50const { BaseDriver } = require('app

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('test', function () {2 it('should log the response', function () {3 driver.requestEndLoggingFormat();4 });5});6describe('test', function () {7 it('should log the response', function () {8 driver.requestEndLoggingFormat();9 });10});11describe('test', function () {12 it('should log the response', function () {13 driver.requestEndLoggingFormat();14 });15});16describe('test', function () {17 it('should log the response', function () {18 driver.requestEndLoggingFormat();19 });20});21describe('test', function () {22 it('should log the response', function () {23 driver.requestEndLoggingFormat();24 });25});26describe('test', function () {27 it('should log the response', function () {28 driver.requestEndLoggingFormat();29 });30});31describe('test', function () {32 it('should log the response', function () {33 driver.requestEndLoggingFormat();34 });35});36describe('test', function () {37 it('should log the response', function () {38 driver.requestEndLoggingFormat();39 });40});41describe('test', function () {42 it('should log the response', function () {43 driver.requestEndLoggingFormat();44 });45});46describe('test', function () {47 it('should log the response', function () {48 driver.requestEndLoggingFormat();49 });50});51describe('test', function () {

Full Screen

Using AI Code Generation

copy

Full Screen

1const requestEndLoggingFormat = require('appium-base-driver').requestEndLoggingFormat;2const logFormat = requestEndLoggingFormat('GET', '/wd/hub/session/:sessionId/element/:elementId/displayed', {3});4console.log(logFormat);5const responseEndLoggingFormat = require('appium-base-driver').responseEndLoggingFormat;6const logFormat = responseEndLoggingFormat('GET', '/wd/hub/session/:sessionId/element/:elementId/displayed', {7}, 'true');8console.log(logFormat);9const requestErrorLoggingFormat = require('appium-base-driver').requestErrorLoggingFormat;10const logFormat = requestErrorLoggingFormat('GET', '/wd/hub/session/:sessionId/element/:elementId/displayed', {11}, 'Element not found');12console.log(logFormat);13const responseErrorLoggingFormat = require('appium-base-driver').responseErrorLoggingFormat;14const logFormat = responseErrorLoggingFormat('GET', '/wd/hub/session/:sessionId/element/:elementId/displayed', {15}, 'Element not found');16console.log(logFormat);

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 Appium Base Driver 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