How to use finishStartingLogCapture method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

Run Appium Xcuitest Driver automation tests on LambdaTest cloud grid

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

Sign up Free
_

ios-log.js

Source: ios-log.js Github

copy
1import path from 'path';
2import _ from 'lodash';
3import logger from './logger';
4import { fs, mkdirp } from 'appium-support';
5import xcode from 'appium-xcode';
6import { SubProcess } from 'teen_process';
7
8
9// Date-Utils: Polyfills for the Date object
10require('date-utils');
11
12
13const START_TIMEOUT = 10000;
14const DEVICE_CONSOLE_PATH = path.resolve(__dirname, '..', '..', '..', 'build', 'deviceconsole');
15const SYSTEM_LOG_PATH = '/var/log/system.log';
16
17class IOSLog {
18  constructor (opts) {
19    this.sim = opts.sim;
20    this.udid = opts.udid;
21    this.showLogs = !!opts.showLogs;
22
23    this.proc = null;
24    this.iosLogStartTime = null;
25    this.loggingModeOn = true;
26    this.logs = [];
27    this.logRow = '';
28    this.logsSinceLastRequest = [];
29
30    // method to save the time of the first log
31    this.logsStarted = _.once(function () {
32      this.iosLogStartTime = new Date();
33    });
34  }
35
36  async startCaptureRealDevice () {
37    this.loggingModeOn = false;
38    let spawnEnv = _.clone(process.env);
39    logger.debug('Attempting iOS device log capture via libimobiledevice idevicesyslog');
40    try {
41      let idevicesyslog = await fs.which('idevicesyslog');
42      logger.debug(`Found idevicesyslog: '${idevicesyslog}'`);
43      this.proc = new SubProcess('idevicesyslog', ['-u', this.udid], {env: spawnEnv});
44    } catch (err) {
45      logger.warn('Could not capture device log using libimobiledevice idevicesyslog. ' +
46                  'Libimobiledevice is probably not installed');
47      logger.debug('Attempting iOS device log capture via deviceconsole');
48      spawnEnv.PATH = `${process.env.PATH}:${DEVICE_CONSOLE_PATH}`;
49      spawnEnv.DYLD_LIBRARY_PATH = `${DEVICE_CONSOLE_PATH}:${process.env.DYLD_LIBRARY_PATH}`;
50      this.proc = new SubProcess('deviceconsole', ['-u', this.udid], {env: spawnEnv});
51    }
52    await this.finishStartingLogCapture();
53  }
54
55  async startCapture () {
56    if (this.udid) { // if we have a real device
57      return this.startCaptureRealDevice();
58    }
59    // otherwise, if we have a simulator...
60    let xCodeVersion = await xcode.getVersion(true);
61
62    logger.debug(`Starting iOS ${await this.sim.getPlatformVersion()} simulator log capture`);
63    if (xCodeVersion.major < 5) {
64      this.proc = new SubProcess('tail', ['-f', '-n', '1', SYSTEM_LOG_PATH]);
65      await this.finishStartingLogCapture();
66      return;
67    }
68
69    // this is xcode 6+
70    if (_.isUndefined(this.sim.udid)) {
71      logger.errorAndThrow(`iOS ${xCodeVersion.versionString} log capture requires a sim udid`);
72    }
73
74    let logPath = this.sim.getLogDir();
75    try {
76      if (logPath.indexOf('*') >= 0) {
77        logger.error(`Log path has * in it. Unable to start log capture: ${logPath}`);
78        return;
79      }
80      let systemLogPath = path.resolve(logPath, 'system.log');
81      logger.debug(`System log path: ${systemLogPath}`);
82      await mkdirp(logPath);
83      await fs.writeFile(systemLogPath, 'A new Appium session is about to start!\n', {flag: 'a'});
84      let files;
85      try {
86        files = await fs.glob(systemLogPath);
87        if (files.length < 1) {
88          throw new Error('Could not start log capture');
89        }
90      } catch (e) {
91        logger.error(`Could not start log capture because no iOS ` +
92                     `simulator logs could be found at ${systemLogPath}. ` +
93                     `Logging will not be functional for this run`);
94      }
95
96      let lastModifiedLogPath = files[0];
97      let lastModifiedLogTime = await fs.stat(lastModifiedLogPath).mtime;
98      for (let file of files) {
99        let mtime = await fs.stat(file).mtime;
100        if (mtime > lastModifiedLogTime) {
101          lastModifiedLogPath = file;
102          lastModifiedLogTime = mtime;
103        }
104      }
105      this.proc = new SubProcess('tail', ['-f', '-n', '1', lastModifiedLogPath]);
106      await this.finishStartingLogCapture();
107    } catch (err) {
108      logger.errorAndThrow(`System log capture failed: ${err.message}`);
109    }
110  }
111
112  async finishStartingLogCapture () {
113    if (!this.proc) {
114      logger.errorAndThrow('Could not capture device log');
115    }
116    let firstLine = true;
117    this.proc.on('output', (stdout, stderr) => {
118      if (stdout) {
119        if (firstLine) {
120          if (stdout.substr(-1, 1) === '\n') {
121            // don't store the first line of the log because it came before the sim or device was launched
122            firstLine = false;
123          }
124        } else {
125          this.logRow += stdout;
126          if (stdout.substr(-1, 1) === '\n') {
127            this.onOutput();
128            this.logRow = '';
129          }
130        }
131      }
132      if (stderr) {
133        this.onOutput('STDERR');
134      }
135    });
136
137    let sd = (stdout, stderr) => {
138      if (/execvp\(\)/.test(stderr)) {
139        throw new Error('iOS log capture process failed to start');
140      }
141      return stdout || stderr;
142    };
143    await this.proc.start(sd, START_TIMEOUT);
144  }
145
146  async stopCapture () {
147    logger.debug('Stopping iOS log capture');
148    if (this.proc && this.proc.isRunning) {
149      await this.proc.stop();
150    }
151    this.proc = null;
152  }
153
154  onOutput (prefix = '') {
155    this.logsStarted();
156
157    let logs = this.logRow.split('\n');
158    for (let log of logs) {
159      if (log) {
160        if (!this.loggingModeOn) {
161          // figure out if this log row marks the beginning of our log capture or not
162          let logRowParts = log.split(/\s+/);
163          let logRowDate = new Date(`${this.iosLogStartTime.getFullYear()} ${logRowParts[0]} ${logRowParts[1]} ${logRowParts[2]}`);
164          if (logRowDate.isAfter(this.iosLogStartTime)) {
165            this.loggingModeOn = true;
166          }
167        }
168        if (this.loggingModeOn) {
169          let logObj = {
170            timestamp: Date.now(),
171            level: 'ALL',
172            message: log
173          };
174          this.logs.push(logObj);
175          this.logsSinceLastRequest.push(logObj);
176          if (this.showLogs) {
177            let space = prefix.length > 0 ? ' ' : '';
178            logger.info(`[IOS_SYSLOG_ROW${space}${prefix}] ${log}`);
179          }
180        }
181      }
182    }
183  }
184
185  async getLogs () {
186    let ret = this.logsSinceLastRequest;
187    this.logsSinceLastRequest = [];
188    return ret;
189  }
190
191  async getAllLogs () {
192    return this.logs;
193  }
194}
195
196export default IOSLog;
197
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Appium Xcuitest Driver on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)