Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(logger): update logging methods #5

Merged
merged 1 commit into from
Apr 22, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/webdriver-manager
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ var fs = require('fs');

var cwd = process.cwd();
var dir = __dirname;
var localInstall = path.resolve(cwd, 'node_modules/webdriver-tool/');
var localInstall = path.resolve(cwd, 'node_modules/webdriver-manager/');
var parentPath = path.resolve(cwd, '..');
var folder = cwd.replace(parentPath, '').substring(1);

Expand Down
1 change: 0 additions & 1 deletion lib/cli/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import * as chalk from 'chalk';
import * as path from 'path';

import {Config} from '../config';
import {Logger} from './util';
import {Programs, Program} from './programs';
import {MinimistArgs, Options} from './options';

Expand Down
2 changes: 1 addition & 1 deletion lib/cli/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export * from './cli';
export * from './options';
export * from './programs';
export * from './util';
export * from './logger';
258 changes: 258 additions & 0 deletions lib/cli/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
import * as fs from 'fs';
import * as path from 'path';

// Will use chalk if chalk is available to add color to console logging
let chalk: any;
let printRed: Function;
let printYellow: Function;
let printGray: Function;

try {
chalk = require('chalk');
printRed = chalk.red;
printYellow = chalk.yellow;
printGray = chalk.gray;
} catch (e) {
printRed = printYellow = printGray = (msg: any) => { return msg; };
}

export enum LogLevel {
ERROR,
WARN,
INFO,
DEBUG
}

export enum WriteTo {
CONSOLE,
FILE,
BOTH,
NONE
}

let logFile = 'webdriver.log'; // the default log file name

/**
* Logger class adds timestamp output, log levels, and identifiers to help
* when debugging. Also could write to console, file, both, or none.
*/
export class Logger {
static logLevel: LogLevel = LogLevel.INFO;
static showTimestamp: boolean = true;
static showId: boolean = true;
static writeTo: WriteTo = WriteTo.CONSOLE;
static fd: any;
static firstWrite: boolean = false;

/**
* Set up the write location. If writing to a file, get the file descriptor.
* @param writeTo The enum for where to write the logs.
* @param opt_logFile An optional parameter to override the log file location.
*/
static setWrite(writeTo: WriteTo, opt_logFile?: string): void {
if (opt_logFile) {
logFile = opt_logFile;
}
Logger.writeTo = writeTo;
if (Logger.writeTo == WriteTo.FILE || Logger.writeTo == WriteTo.BOTH) {
Logger.fd = fs.openSync(path.resolve(logFile), 'a');
Logger.firstWrite = false;
}
}

/**
* Creates a logger instance with an ID for the logger.
* @constructor
*/
constructor(private id: string) {}

/**
* Log INFO
* @param ...msgs multiple arguments to be logged.
*/
info(...msgs: any[]): void { this.log_(LogLevel.INFO, msgs); }

/**
* Log DEBUG
* @param ...msgs multiple arguments to be logged.
*/
debug(...msgs: any[]): void { this.log_(LogLevel.DEBUG, msgs); }

/**
* Log WARN
* @param ...msgs multiple arguments to be logged.
*/
warn(...msgs: any[]): void { this.log_(LogLevel.WARN, msgs); }

/**
* Log ERROR
* @param ...msgs multiple arguments to be logged.
*/
error(...msgs: any[]): void { this.log_(LogLevel.ERROR, msgs); }

/**
* For the log level set, check to see if the messages should be logged.
* @param logLevel The log level of the message.
* @param msgs The messages to be logged
*/
log_(logLevel: LogLevel, msgs: any[]): void {
switch (Logger.logLevel) {
case LogLevel.ERROR:
if (logLevel <= LogLevel.ERROR) {
this.print_(logLevel, msgs);
}
break;
case LogLevel.WARN:
if (logLevel <= LogLevel.WARN) {
this.print_(logLevel, msgs);
}
break;
case LogLevel.INFO:
if (logLevel <= LogLevel.INFO) {
this.print_(logLevel, msgs);
}
break;
case LogLevel.DEBUG:
if (logLevel <= LogLevel.DEBUG) {
this.print_(logLevel, msgs);
}
break;
default:
throw new Error('Log level undefined');
}
}

/**
* Format with timestamp, log level, identifier, and message and log to
* specified medium (console, file, both, none).
* @param logLevel The log level of the message.
* @param msgs The messages to be logged.
*/
print_(logLevel: LogLevel, msgs: any[]): void {
let consoleLog: string = '';
let fileLog: string = '';

if (Logger.showTimestamp) {
consoleLog += Logger.timestamp_(WriteTo.CONSOLE);
fileLog += Logger.timestamp_(WriteTo.FILE);
}
consoleLog += Logger.level_(logLevel, this.id, WriteTo.CONSOLE);
fileLog += Logger.level_(logLevel, this.id, WriteTo.FILE);
if (Logger.showId) {
consoleLog += Logger.id_(logLevel, this.id, WriteTo.CONSOLE);
fileLog += Logger.id_(logLevel, this.id, WriteTo.FILE);
}
consoleLog += ' -';
fileLog += ' - ';

switch (Logger.writeTo) {
case WriteTo.CONSOLE:
msgs.unshift(consoleLog);
console.log.apply(console, msgs);
break;
case WriteTo.FILE:
// for the first line written to the file, add a space
if (!Logger.firstWrite) {
fs.writeSync(Logger.fd, '\n');
Logger.firstWrite = true;
}
fileLog += ' ' + Logger.msgToFile_(msgs);
fs.writeSync(Logger.fd, fileLog + '\n');
break;
case WriteTo.BOTH:
// for the first line written to the file, add a space
if (!Logger.firstWrite) {
fs.writeSync(Logger.fd, '\n');
Logger.firstWrite = true;
}
fileLog += ' ' + Logger.msgToFile_(msgs);
fs.writeSync(Logger.fd, fileLog + '\n');
msgs.unshift(consoleLog);
console.log.apply(console, msgs);
break;
case WriteTo.NONE:
break;
}
}

/**
* Get a timestamp formatted with [hh:mm:ss]
* @param writeTo The enum for where to write the logs.
* @return The string of the formatted timestamp
*/
static timestamp_(writeTo: WriteTo): string {
let d = new Date();
let ts = '[';
let hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
let minutes = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
let seconds = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds();
if (writeTo == WriteTo.CONSOLE) {
ts += printGray(hours + ':' + minutes + ':' + seconds) + ']';
} else {
ts += hours + ':' + minutes + ':' + seconds + ']';
}
ts += ' ';
return ts;
}

/**
* Get the identifier of the logger as '/<id>'
* @param logLevel The log level of the message.
* @param writeTo The enum for where to write the logs.
* @return The string of the formatted id
*/
static id_(logLevel: LogLevel, id: string, writeTo: WriteTo): string {
let level = LogLevel[logLevel].toString();
if (writeTo === WriteTo.FILE) {
return '/' + id;
} else if (logLevel === LogLevel.ERROR) {
return printRed('/' + id);
} else if (logLevel === LogLevel.WARN) {
return printYellow('/' + id);
} else {
return '/' + id;
}
}

/**
* Get the log level formatted with the first letter. For info, it is I.
* @param logLevel The log level of the message.
* @param writeTo The enum for where to write the logs.
* @return The string of the formatted log level
*/
static level_(logLevel: LogLevel, id: string, writeTo: WriteTo): string {
let level = LogLevel[logLevel].toString();
if (writeTo === WriteTo.FILE) {
return level[0];
} else if (logLevel === LogLevel.ERROR) {
return printRed(level[0]);
} else if (logLevel === LogLevel.WARN) {
return printYellow(level[0]);
} else {
return level[0];
}
}

/**
* Convert the list of messages to a single string message.
* @param msgs The list of messages.
* @return The string of the formatted messages
*/
static msgToFile_(msgs: any[]): string {
let log = '';
for (let pos = 0; pos < msgs.length; pos++) {
let msg = msgs[pos];
let ret: any;
if (typeof msg === 'object') {
ret = JSON.stringify(msg);
} else {
ret = msg;
}
if (pos !== msgs.length - 1) {
ret += ' ';
}
log += ret;
}
return log;
}
}
36 changes: 0 additions & 36 deletions lib/cli/util.ts

This file was deleted.

13 changes: 7 additions & 6 deletions lib/cmds/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {FileManager} from '../files';
import {Logger, Options, Program} from '../cli';
import {BinaryMap, ChromeDriver, IEDriver, StandAlone} from '../binaries';

let logger = new Logger('start');
let prog = new Program()
.command('start', 'start up the selenium server')
.action(start)
Expand Down Expand Up @@ -66,7 +67,7 @@ function start(options: Options) {
let downloadedBinaries = FileManager.downloadedBinaries(outputDir);

if (downloadedBinaries[StandAlone.id] == null) {
Logger.error(
logger.error(
'Selenium Standalone is not present. Install with ' +
'webdriver-manager update --standalone');
process.exit(1);
Expand Down Expand Up @@ -94,21 +95,21 @@ function start(options: Options) {
for (let arg in args) {
argsToString += ' ' + args[arg];
}
Logger.info('java' + argsToString);
logger.info('java' + argsToString);

let seleniumProcess = spawnCommand('java', args);
Logger.info('seleniumProcess.pid: ' + seleniumProcess.pid);
logger.info('seleniumProcess.pid: ' + seleniumProcess.pid);
seleniumProcess.on('exit', (code: number) => {
Logger.info('Selenium Standalone has exited with code ' + code);
logger.info('Selenium Standalone has exited with code ' + code);
process.exit(code);
});
process.stdin.resume();
process.stdin.on('data', (chunk: Buffer) => {
Logger.info('Attempting to shut down selenium nicely');
logger.info('Attempting to shut down selenium nicely');
http.get('http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer');
});
process.on('SIGINT', () => {
Logger.info('Staying alive until the Selenium Standalone process exits');
logger.info('Staying alive until the Selenium Standalone process exits');
});
}

Expand Down
5 changes: 3 additions & 2 deletions lib/cmds/status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {Config} from '../config';
import {FileManager} from '../files';
import {Logger, Options, Program} from '../cli';

let logger = new Logger('status');
let prog = new Program()
.command('status', 'list the current available drivers')
.addOption(Opts[Opt.OUT_DIR])
Expand Down Expand Up @@ -52,12 +53,12 @@ function status(options: Options) {
log += ', ';
}
}
Logger.info(log);
logger.info(log);
}
// for binaries that are available for the operating system, show them here
for (let bin in binaries) {
if (downloadedBinaries[bin] == null) {
Logger.info(binaries[bin].name + ' is not present');
logger.info(binaries[bin].name + ' is not present');
}
}
}
Loading