Skip to content

Commit

Permalink
feat: showOutput option & log function (#185)
Browse files Browse the repository at this point in the history
* feat: showOutput option & log function

* logger class

* doc update
  • Loading branch information
santoshjoseph99 authored and denar90 committed Aug 21, 2018
1 parent 6ff77b9 commit f4cbe0f
Show file tree
Hide file tree
Showing 10 changed files with 82 additions and 28 deletions.
8 changes: 5 additions & 3 deletions lib/chart/chart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const wunderbar = require('@gribnoysup/wunderbar');
const eol = require('os').EOL;

import {Timing, ChartOptions} from '../../types/types';
const Logger = require('../utils/logger');
const logger = Logger.getInstance();

const drawChart = (timings: Timing[], options: ChartOptions) => {
const {lmargin, width, xlabel, xmin, xmax} = options;
Expand Down Expand Up @@ -47,9 +49,9 @@ const drawChart = (timings: Timing[], options: ChartOptions) => {

const chartScale = `${padding} ${minValueFormatted}${labelPadding}${xlabel}${labelPadding}${maxValueFormatted}`;

console.log();
console.log([chartTop, chart, chartBottom, chartScale].join(eol));
console.log();
logger.log('');
logger.log([chartTop, chart, chartBottom, chartScale].join(eol));
logger.log('');
};

module.exports = drawChart;
6 changes: 4 additions & 2 deletions lib/drive/gdrive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ const promisify = require('micro-promisify');
import { Oauth2Client, AuthorizeCredentials, DriveResponse } from '../../types/types';
const GoogleOauth = require('../oauth/google-oauth');
const messages = require('../utils/messages');
const Logger = require('../utils/logger');
const logger = Logger.getInstance();

class GDrive {
private oauth: Oauth2Client;
Expand All @@ -26,7 +28,7 @@ class GDrive {

async uploadToDrive(data: any, fileName: string): Promise<DriveResponse> {
try {
console.log(messages.getMessage('G_DRIVE_UPLOADING'));
logger.log(messages.getMessage('G_DRIVE_UPLOADING'));
const drive = google.drive({
version: 'v3',
auth: await this.getOauth()
Expand All @@ -45,7 +47,7 @@ class GDrive {

const driveResponse: DriveResponse = await promisify(drive.files.create)(body);
await this.setSharingPermissions(driveResponse.id);
console.log(messages.getMessage('G_DRIVE_UPLOADED'));
logger.log(messages.getMessage('G_DRIVE_UPLOADED'));
return driveResponse;
} catch (error) {
throw new Error(error);
Expand Down
8 changes: 5 additions & 3 deletions lib/expectations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,20 @@

import { Timing, ExpectationMetrics, NormalizedExpectationMetrics } from '../types/types';
const { getAssertionMessage, getMessageWithPrefix } = require('./utils/messages');
const Logger = require('./utils/logger');
const logger = Logger.getInstance();

function validateMetrics(metrics: ExpectationMetrics) {
const metricsKeys = Object.keys(metrics);

if (!metrics || !metricsKeys.length) {
console.error(getMessageWithPrefix('ERROR', 'NO_METRICS'));
logger.error(getMessageWithPrefix('ERROR', 'NO_METRICS'));
process.exit(1);
}

metricsKeys.forEach(key => {
if (!metrics[key] || !metrics[key].warn || !metrics[key].error) {
console.error(getMessageWithPrefix('ERROR', 'NO_EXPECTATION_ERROR', key));
logger.error(getMessageWithPrefix('ERROR', 'NO_EXPECTATION_ERROR', key));
process.exit(1);
}
});
Expand Down Expand Up @@ -47,7 +49,7 @@ function checkExpectations(metricsData: Timing[], expectationMetrics: Normalized
}

if (msg) {
console.log(msg);
logger.log(msg);
}
});
}
Expand Down
27 changes: 16 additions & 11 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const expectations = require('./expectations');
const {upload} = require('./upload');
const messages = require('./utils/messages');
const drawChart = require('./chart/chart');
const Logger = require('./utils/logger');

import {
MainOptions,
Expand All @@ -41,7 +42,8 @@ class PWMetrics {
view: false,
expectations: false,
json: false,
chromeFlags: ''
chromeFlags: '',
showOutput: true
};
runs: number;
sheets: SheetsConfig;
Expand All @@ -50,6 +52,7 @@ class PWMetrics {
tryLighthouseCounter: number;
launcher: LaunchedChrome;
parsedChromeFlags: Array<string>;
logger: any;

constructor(public url: string, opts: MainOptions) {
this.flags = Object.assign({}, this.flags, opts.flags);
Expand All @@ -72,6 +75,8 @@ class PWMetrics {
}

this.parsedChromeFlags = parseChromeFlags(this.flags.chromeFlags);

this.logger = Logger.getInstance({showOutput: this.flags.showOutput});
}

async start() {
Expand All @@ -87,18 +92,18 @@ class PWMetrics {
resultHasExpectationErrors = this.resultHasExpectationErrors(currentMetricResult);
}
metricsResults[runIndex] = currentMetricResult;
console.log(messages.getMessageWithPrefix('SUCCESS', 'SUCCESS_RUN', runIndex, runs.length));
this.logger.log(messages.getMessageWithPrefix('SUCCESS', 'SUCCESS_RUN', runIndex, runs.length));
} catch (error) {
metricsResults[runIndex] = error;
console.error(messages.getMessageWithPrefix('ERROR', 'FAILED_RUN', runIndex, runs.length, error.message));
this.logger.error(messages.getMessageWithPrefix('ERROR', 'FAILED_RUN', runIndex, runs.length, error.message));
}
}

let results: PWMetricsResults = { runs: metricsResults.filter(r => !(r instanceof Error)) };
if (results.runs.length > 0) {
if (this.runs > 1 && !this.flags.submit) {
results.median = this.findMedianRun(results.runs);
console.log(messages.getMessage('MEDIAN_RUN'));
this.logger.log(messages.getMessage('MEDIAN_RUN'));
this.displayOutput(results.median);
} else if (this.flags.submit) {
const sheets = new Sheets(this.sheets, this.clientSecret);
Expand Down Expand Up @@ -135,7 +140,7 @@ class PWMetrics {
lhResults = await this.runLighthouseOnCI().then((lhResults:LighthouseResults) => {
// fix for https://github.com/paulirish/pwmetrics/issues/63
return new Promise<LighthouseResults>(resolve => {
console.log(messages.getMessage('WAITING'));
this.logger.log(messages.getMessage('WAITING'));
setTimeout(_ => {
return resolve(lhResults);
}, 2000);
Expand Down Expand Up @@ -177,20 +182,20 @@ class PWMetrics {

async retryLighthouseOnCI(): Promise<LighthouseResults> {
this.tryLighthouseCounter++;
console.log(messages.getMessage('CRI_TIMEOUT_RELAUNCH'));
this.logger.log(messages.getMessage('CRI_TIMEOUT_RELAUNCH'));

try {
return await this.runLighthouseOnCI();
} catch(error) {
console.error(error.message);
console.error(messages.getMessage('CLOSING_CHROME'));
this.logger.error(error.message);
this.logger.error(messages.getMessage('CLOSING_CHROME'));
await this.killLauncher();
}
}

async launchChrome(): Promise<LaunchedChrome|Error> {
try {
console.log(messages.getMessage('LAUNCHING_CHROME'));
this.logger.log(messages.getMessage('LAUNCHING_CHROME'));
this.launcher = await launch({
port: this.flags.port,
chromeFlags: this.parsedChromeFlags,
Expand All @@ -199,7 +204,7 @@ class PWMetrics {
this.flags.port = this.launcher.port;
return this.launcher;
} catch(error) {
console.error(error);
this.logger.error(error);
await this.killLauncher();
return error;
}
Expand Down Expand Up @@ -242,7 +247,7 @@ class PWMetrics {
timings = timings.filter(r => {
// filter out metrics that failed to record
if (r.timing === undefined || isNaN(r.timing)) {
console.error(messages.getMessageWithPrefix('ERROR', 'METRIC_IS_UNAVAILABLE', r.title));
this.logger.log(messages.getMessageWithPrefix('ERROR', 'METRIC_IS_UNAVAILABLE', r.title));
return false;
}
// don't chart hidden metrics, but include in json
Expand Down
4 changes: 3 additions & 1 deletion lib/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import {MetricsResults, MetricsDefinition, Timing, Timestamp, LighthouseResults, LighthouseAudits} from '../types/types';

const metricsDefinitions: MetricsDefinition[] = require('lighthouse/lighthouse-core/lib/traces/pwmetrics-events.js').metricsDefinitions;
const Logger = require('./utils/logger');
const logger = Logger.getInstance();

const metricsIds = {
NAVSTART: 'navstart',
Expand Down Expand Up @@ -38,7 +40,7 @@ module.exports = {
const checkAudits = (audits: LighthouseAudits) => Object.keys(audits).forEach(key => {
const debugString = audits[key].debugString;
if (audits[key].debugString)
console.log(`${debugString} Audit key: ${key}`);
logger.log(`${debugString} Audit key: ${key}`);
});

function prepareData(res: LighthouseResults): MetricsResults {
Expand Down
4 changes: 3 additions & 1 deletion lib/oauth/google-oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const readlineSync = require('readline-sync');
const { getMessage } = require('../utils/messages');

import { AuthorizeCredentials, Oauth2Client } from '../../types/types';
const Logger = require('../utils/logger');
const logger = Logger.getInstance();

/* improve the bad polyfill that devtools-frontend did */
//@todo remove after https://github.com/GoogleChrome/lighthouse/issues/1535 will be closed
Expand Down Expand Up @@ -103,7 +105,7 @@ class GoogleOauth {
}
}
fs.writeFileSync(this.tokenPath, JSON.stringify(token));
console.log(getMessage('G_OAUTH_STORED_TOKEN', this.tokenPath));
logger.log(getMessage('G_OAUTH_STORED_TOKEN', this.tokenPath));
}
}

Expand Down
10 changes: 6 additions & 4 deletions lib/sheets/gsheets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ const promisify = require('micro-promisify');
const { getMessage } = require('../utils/messages');

import { Oauth2Client, GSheetsAppendResultsOptions, GSheetsValuesToAppend } from '../../types/types';
const Logger = require('../utils/logger');
const logger = Logger.getInstance();

async function getRange(auth: Oauth2Client, range: number, spreadsheetId: string): Promise<Array<GSheetsValuesToAppend>> {
try {
Expand All @@ -18,7 +20,7 @@ async function getRange(auth: Oauth2Client, range: number, spreadsheetId: string
});
return response.values;
} catch(error) {
console.log(getMessage('G_SHEETS_API_ERROR', error));
logger.error(getMessage('G_SHEETS_API_ERROR', error));
throw new Error(error);
}
}
Expand All @@ -35,7 +37,7 @@ async function appendResults(auth: Oauth2Client, valuesToAppend: Array<GSheetsVa
const sheets = google.sheets('v4');
// clone values to append
const values = Object.assign([], valuesToAppend);
console.log(getMessage('G_SHEETS_APPENDING', formatValues(valuesToAppend)));
logger.log(getMessage('G_SHEETS_APPENDING', formatValues(valuesToAppend)));

const response = await promisify(sheets.spreadsheets.values.append)({
auth: auth,
Expand All @@ -47,9 +49,9 @@ async function appendResults(auth: Oauth2Client, valuesToAppend: Array<GSheetsVa
},
});
const rangeValues: Array<GSheetsValuesToAppend> = await getRange(auth, response.updates.updatedRange, options.spreadsheetId);
console.log(getMessage('G_SHEETS_APPENDED', formatValues(rangeValues)));
logger.log(getMessage('G_SHEETS_APPENDED', formatValues(rangeValues)));
} catch(error) {
console.log(getMessage('G_SHEETS_API_ERROR', error));
log.error(getMessage('G_SHEETS_API_ERROR', error));
throw new Error(error);
}
}
Expand Down
30 changes: 30 additions & 0 deletions lib/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { LoggerOptions} from '../../types/types';

class Logger {
static options: LoggerOptions = {
showOutput: true
}
private static instance: Logger;

constructor() {}

static getInstance(options: LoggerOptions = null) {
Logger.options = options || Logger.options;
Logger.instance = Logger.instance || new Logger();
return Logger.instance;
}

log(msg: any, ...args: any[]) {
if(Logger.options.showOutput){
console.log(msg, ...args);
}
}

error(msg: any, ...args: any[]) {
if(Logger.options.showOutput){
console.error(msg, ...args);
}
}
}

module.exports = Logger;
3 changes: 2 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,9 @@ module.exports = {
json: true, // not required, set to true if you want json output
outputPath: 'stdout', // not required, only needed if you have specified json output, can be "stdout" or a path
chromePath: '/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary', //optional path to specific Chrome location
chromeFlags: '' // custom flags to pass to Chrome. For a full list of flags, see http://peter.sh/experiments/chromium-command-line-switches/.
chromeFlags: '', // custom flags to pass to Chrome. For a full list of flags, see http://peter.sh/experiments/chromium-command-line-switches/.
// Note: pwmetrics supports all flags from Lighthouse
showOutput: true // not required, set to false for pwmetrics not output any console.log messages
},
expectations: {
// these expectations values are examples, for your cases set your own
Expand Down
10 changes: 8 additions & 2 deletions types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ interface FeatureFlags {
expectations: Boolean;
json: Boolean;
chromeFlags: string;
chromePath?: string
chromePath?: string;
port?: number;
showOutput: Boolean;
}

interface MetricsResults {
Expand Down Expand Up @@ -155,6 +156,10 @@ interface ChartOptions {
lmargin: number;
};

interface LoggerOptions {
showOutput: Boolean;
}

export {
Timing,
Timestamp,
Expand All @@ -175,5 +180,6 @@ export {
FeatureFlags,
TermWritableStream,
PWMetricsResults,
ChartOptions
ChartOptions,
LoggerOptions
};

0 comments on commit f4cbe0f

Please sign in to comment.