Path: blob/trunk/javascript/selenium-webdriver/lib/logging.js
4505 views
// Licensed to the Software Freedom Conservancy (SFC) under one1// or more contributor license agreements. See the NOTICE file2// distributed with this work for additional information3// regarding copyright ownership. The SFC licenses this file4// to you under the Apache License, Version 2.0 (the5// "License"); you may not use this file except in compliance6// with the License. You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing,11// software distributed under the License is distributed on an12// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13// KIND, either express or implied. See the License for the14// specific language governing permissions and limitations15// under the License.1617'use strict'1819/**20* @fileoverview Defines WebDriver's logging system. The logging system is21* broken into major components: local and remote logging.22*23* The local logging API, which is anchored by the {@linkplain Logger} class is24* similar to Java's logging API. Loggers, retrieved by25* {@linkplain #getLogger getLogger(name)}, use hierarchical, dot-delimited26* namespaces (e.g. "" > "webdriver" > "webdriver.logging"). Recorded log27* messages are represented by the {@linkplain Entry} class. You can capture log28* records by {@linkplain Logger#addHandler attaching} a handler function to the29* desired logger. For convenience, you can quickly enable logging to the30* console by simply calling {@linkplain #installConsoleHandler31* installConsoleHandler}.32*33* The [remote logging API](https://github.com/SeleniumHQ/selenium/wiki/Logging)34* allows you to retrieve logs from a remote WebDriver server. This API uses the35* {@link Preferences} class to define desired log levels prior to creating36* a WebDriver session:37*38* var prefs = new logging.Preferences();39* prefs.setLevel(logging.Type.BROWSER, logging.Level.DEBUG);40*41* var caps = Capabilities.chrome();42* caps.setLoggingPrefs(prefs);43* // ...44*45* Remote log entries, also represented by the {@link Entry} class, may be46* retrieved via {@link webdriver.WebDriver.Logs}:47*48* driver.manage().logs().get(logging.Type.BROWSER)49* .then(function(entries) {50* entries.forEach(function(entry) {51* console.log('[%s] %s', entry.level.name, entry.message);52* });53* });54*55* **NOTE:** Only a few browsers support the remote logging API (notably56* Firefox and Chrome). Firefox supports basic logging functionality, while57* Chrome exposes robust58* [performance logging](https://chromedriver.chromium.org/logging)59* options. Remote logging is still considered a non-standard feature, and the60* APIs exposed by this module for it are non-frozen. This module will be61* updated, possibly breaking backwards-compatibility, once logging is62* officially defined by the63* [W3C WebDriver spec](http://www.w3.org/TR/webdriver/).64*/6566/**67* Defines a message level that may be used to control logging output.68*69* @final70*/71class Level {72/**73* @param {string} name the level's name.74* @param {number} level the level's numeric value.75*/76constructor(name, level) {77if (level < 0) {78throw new TypeError('Level must be >= 0')79}8081/** @private {string} */82this.name_ = name8384/** @private {number} */85this.value_ = level86}8788/** This logger's name. */89get name() {90return this.name_91}9293/** The numeric log level. */94get value() {95return this.value_96}9798/** @override */99toString() {100return this.name101}102}103104/**105* Indicates no log messages should be recorded.106* @const107*/108Level.OFF = new Level('OFF', Infinity)109110/**111* Log messages with a level of `1000` or higher.112* @const113*/114Level.SEVERE = new Level('SEVERE', 1000)115116/**117* Log messages with a level of `900` or higher.118* @const119*/120Level.WARNING = new Level('WARNING', 900)121122/**123* Log messages with a level of `800` or higher.124* @const125*/126Level.INFO = new Level('INFO', 800)127128/**129* Log messages with a level of `700` or higher.130* @const131*/132Level.DEBUG = new Level('DEBUG', 700)133134/**135* Log messages with a level of `500` or higher.136* @const137*/138Level.FINE = new Level('FINE', 500)139140/**141* Log messages with a level of `400` or higher.142* @const143*/144Level.FINER = new Level('FINER', 400)145146/**147* Log messages with a level of `300` or higher.148* @const149*/150Level.FINEST = new Level('FINEST', 300)151152/**153* Indicates all log messages should be recorded.154* @const155*/156Level.ALL = new Level('ALL', 0)157158const ALL_LEVELS = /** !Set<Level> */ new Set([159Level.OFF,160Level.SEVERE,161Level.WARNING,162Level.INFO,163Level.DEBUG,164Level.FINE,165Level.FINER,166Level.FINEST,167Level.ALL,168])169170const LEVELS_BY_NAME = /** !Map<string, !Level> */ new Map([171[Level.OFF.name, Level.OFF],172[Level.SEVERE.name, Level.SEVERE],173[Level.WARNING.name, Level.WARNING],174[Level.INFO.name, Level.INFO],175[Level.DEBUG.name, Level.DEBUG],176[Level.FINE.name, Level.FINE],177[Level.FINER.name, Level.FINER],178[Level.FINEST.name, Level.FINEST],179[Level.ALL.name, Level.ALL],180])181182/**183* Converts a level name or value to a {@link Level} value. If the name/value184* is not recognized, {@link Level.ALL} will be returned.185*186* @param {(number|string)} nameOrValue The log level name, or value, to187* convert.188* @return {!Level} The converted level.189*/190function getLevel(nameOrValue) {191if (typeof nameOrValue === 'string') {192return LEVELS_BY_NAME.get(nameOrValue) || Level.ALL193}194if (typeof nameOrValue !== 'number') {195throw new TypeError('not a string or number')196}197for (let level of ALL_LEVELS) {198if (nameOrValue >= level.value) {199return level200}201}202return Level.ALL203}204205/**206* Describes a single log entry.207*208* @final209*/210class Entry {211/**212* @param {(!Level|string|number)} level The entry level.213* @param {string} message The log message.214* @param {number=} opt_timestamp The time this entry was generated, in215* milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the216* current time will be used.217* @param {string=} opt_type The log type, if known.218*/219constructor(level, message, opt_timestamp, opt_type) {220this.level = level instanceof Level ? level : getLevel(level)221this.message = message222this.timestamp = typeof opt_timestamp === 'number' ? opt_timestamp : Date.now()223this.type = opt_type || ''224}225226/**227* @return {{level: string, message: string, timestamp: number,228* type: string}} The JSON representation of this entry.229*/230toJSON() {231return {232level: this.level.name,233message: this.message,234timestamp: this.timestamp,235type: this.type,236}237}238}239240/**241* An object used to log debugging messages. Loggers use a hierarchical,242* dot-separated naming scheme. For instance, "foo" is considered the parent of243* the "foo.bar" and an ancestor of "foo.bar.baz".244*245* Each logger may be assigned a {@linkplain #setLevel log level}, which246* controls which level of messages will be reported to the247* {@linkplain #addHandler handlers} attached to this instance. If a log level248* is not explicitly set on a logger, it will inherit its parent.249*250* This class should never be directly instantiated. Instead, users should251* obtain logger references using the {@linkplain ./logging.getLogger()252* getLogger()} function.253*254* @final255*/256class Logger {257/**258* @param {string} name the name of this logger.259* @param {Level=} opt_level the initial level for this logger.260*/261constructor(name, opt_level) {262/** @private {string} */263this.name_ = name264265/** @private {Level} */266this.level_ = opt_level || null267268/** @private {Logger} */269this.parent_ = null270271/** @private {Set<function(!Entry)>} */272this.handlers_ = null273}274275/** @return {string} the name of this logger. */276getName() {277return this.name_278}279280/**281* @param {Level} level the new level for this logger, or `null` if the logger282* should inherit its level from its parent logger.283*/284setLevel(level) {285this.level_ = level286}287288/** @return {Level} the log level for this logger. */289getLevel() {290return this.level_291}292293/**294* @return {!Level} the effective level for this logger.295*/296getEffectiveLevel() {297let logger = this298let level299do {300level = logger.level_301logger = logger.parent_302} while (logger && !level)303return level || Level.OFF304}305306/**307* @param {!Level} level the level to check.308* @return {boolean} whether messages recorded at the given level are loggable309* by this instance.310*/311isLoggable(level) {312return level.value !== Level.OFF.value && level.value >= this.getEffectiveLevel().value313}314315/**316* Adds a handler to this logger. The handler will be invoked for each message317* logged with this instance, or any of its descendants.318*319* @param {function(!Entry)} handler the handler to add.320*/321addHandler(handler) {322if (!this.handlers_) {323this.handlers_ = new Set()324}325this.handlers_.add(handler)326}327328/**329* Removes a handler from this logger.330*331* @param {function(!Entry)} handler the handler to remove.332* @return {boolean} whether a handler was successfully removed.333*/334removeHandler(handler) {335if (!this.handlers_) {336return false337}338return this.handlers_.delete(handler)339}340341/**342* Logs a message at the given level. The message may be defined as a string343* or as a function that will return the message. If a function is provided,344* it will only be invoked if this logger's345* {@linkplain #getEffectiveLevel() effective log level} includes the given346* `level`.347*348* @param {!Level} level the level at which to log the message.349* @param {(string|function(): string)} loggable the message to log, or a350* function that will return the message.351*/352log(level, loggable) {353if (!this.isLoggable(level)) {354return355}356let message = '[' + this.name_ + '] ' + (typeof loggable === 'function' ? loggable() : loggable)357let entry = new Entry(level, message, Date.now())358for (let logger = this; logger; logger = logger.parent_) {359if (logger.handlers_) {360for (let handler of logger.handlers_) {361handler(entry)362}363}364}365}366367/**368* Logs a message at the {@link Level.SEVERE} log level.369* @param {(string|function(): string)} loggable the message to log, or a370* function that will return the message.371*/372severe(loggable) {373this.log(Level.SEVERE, loggable)374}375376/**377* Logs a message at the {@link Level.WARNING} log level.378* @param {(string|function(): string)} loggable the message to log, or a379* function that will return the message.380*/381warning(loggable) {382this.log(Level.WARNING, loggable)383}384385/**386* Logs a message at the {@link Level.INFO} log level.387* @param {(string|function(): string)} loggable the message to log, or a388* function that will return the message.389*/390info(loggable) {391this.log(Level.INFO, loggable)392}393394/**395* Logs a message at the {@link Level.DEBUG} log level.396* @param {(string|function(): string)} loggable the message to log, or a397* function that will return the message.398*/399debug(loggable) {400this.log(Level.DEBUG, loggable)401}402403/**404* Logs a message at the {@link Level.FINE} log level.405* @param {(string|function(): string)} loggable the message to log, or a406* function that will return the message.407*/408fine(loggable) {409this.log(Level.FINE, loggable)410}411412/**413* Logs a message at the {@link Level.FINER} log level.414* @param {(string|function(): string)} loggable the message to log, or a415* function that will return the message.416*/417finer(loggable) {418this.log(Level.FINER, loggable)419}420421/**422* Logs a message at the {@link Level.FINEST} log level.423* @param {(string|function(): string)} loggable the message to log, or a424* function that will return the message.425*/426finest(loggable) {427this.log(Level.FINEST, loggable)428}429}430431/**432* Maintains a collection of loggers.433*434* @final435*/436class LogManager {437constructor() {438/** @private {!Map<string, !Logger>} */439this.loggers_ = new Map()440this.root_ = new Logger('', Level.OFF)441}442443/**444* Retrieves a named logger, creating it in the process. This function will445* implicitly create the requested logger, and any of its parents, if they446* do not yet exist.447*448* @param {string} name the logger's name.449* @return {!Logger} the requested logger.450*/451getLogger(name) {452if (!name) {453return this.root_454}455let parent = this.root_456for (let i = name.indexOf('.'); i != -1; i = name.indexOf('.', i + 1)) {457let parentName = name.substr(0, i)458parent = this.createLogger_(parentName, parent)459}460return this.createLogger_(name, parent)461}462463/**464* Creates a new logger.465*466* @param {string} name the logger's name.467* @param {!Logger} parent the logger's parent.468* @return {!Logger} the new logger.469* @private470*/471createLogger_(name, parent) {472if (this.loggers_.has(name)) {473return /** @type {!Logger} */ (this.loggers_.get(name))474}475let logger = new Logger(name, null)476logger.parent_ = parent477this.loggers_.set(name, logger)478return logger479}480}481482const logManager = new LogManager()483484// Enable debug logging if SE_DEBUG or SELENIUM_VERBOSE environment variable is set485if (typeof process !== 'undefined' && process.env && (process.env.SE_DEBUG || process.env.SELENIUM_VERBOSE)) {486logManager.root_.setLevel(Level.ALL)487logManager.root_.addHandler(consoleHandler)488if (process.env.SE_DEBUG) {489logManager.root_.warning(490'Environment Variable `SE_DEBUG` is set; Selenium is forcing verbose logging which may override user-specified settings.',491)492}493}494495/**496* Retrieves a named logger, creating it in the process. This function will497* implicitly create the requested logger, and any of its parents, if they498* do not yet exist.499*500* The log level will be unspecified for newly created loggers. Use501* {@link Logger#setLevel(level)} to explicitly set a level.502*503* @param {string} name the logger's name.504* @return {!Logger} the requested logger.505*/506function getLogger(name) {507return logManager.getLogger(name)508}509510/**511* Pads a number to ensure it has a minimum of two digits.512*513* @param {number} n the number to be padded.514* @return {string} the padded number.515*/516function pad(n) {517if (n >= 10) {518return '' + n519} else {520return '0' + n521}522}523524/**525* Logs all messages to the Console API.526* @param {!Entry} entry the entry to log.527*/528function consoleHandler(entry) {529if (typeof console === 'undefined' || !console) {530return531}532533var timestamp = new Date(entry.timestamp)534var msg =535'[' +536timestamp.getUTCFullYear() +537'-' +538pad(timestamp.getUTCMonth() + 1) +539'-' +540pad(timestamp.getUTCDate()) +541'T' +542pad(timestamp.getUTCHours()) +543':' +544pad(timestamp.getUTCMinutes()) +545':' +546pad(timestamp.getUTCSeconds()) +547'Z] ' +548'[' +549entry.level.name +550'] ' +551entry.message552553var level = entry.level.value554if (level >= Level.SEVERE.value) {555console.error(msg)556} else if (level >= Level.WARNING.value) {557console.warn(msg)558} else {559console.log(msg)560}561}562563/**564* Adds the console handler to the given logger. The console handler will log565* all messages using the JavaScript Console API.566*567* @param {Logger=} opt_logger The logger to add the handler to; defaults568* to the root logger.569*/570function addConsoleHandler(opt_logger) {571let logger = opt_logger || logManager.root_572logger.addHandler(consoleHandler)573}574575/**576* Removes the console log handler from the given logger.577*578* @param {Logger=} opt_logger The logger to remove the handler from; defaults579* to the root logger.580* @see exports.addConsoleHandler581*/582function removeConsoleHandler(opt_logger) {583let logger = opt_logger || logManager.root_584logger.removeHandler(consoleHandler)585}586587/**588* Installs the console log handler on the root logger.589*/590function installConsoleHandler() {591addConsoleHandler(logManager.root_)592}593594/**595* Common log types.596* @enum {string}597*/598const Type = {599/** Logs originating from the browser. */600BROWSER: 'browser',601/** Logs from a WebDriver client. */602CLIENT: 'client',603/** Logs from a WebDriver implementation. */604DRIVER: 'driver',605/** Logs related to performance. */606PERFORMANCE: 'performance',607/** Logs from the remote server. */608SERVER: 'server',609}610611/**612* Describes the log preferences for a WebDriver session.613*614* @final615*/616class Preferences {617constructor() {618/** @private {!Map<string, !Level>} */619this.prefs_ = new Map()620}621622/**623* Sets the desired logging level for a particular log type.624* @param {(string|Type)} type The log type.625* @param {(!Level|string|number)} level The desired log level.626* @throws {TypeError} if `type` is not a `string`.627*/628setLevel(type, level) {629if (typeof type !== 'string') {630throw TypeError('specified log type is not a string: ' + typeof type)631}632this.prefs_.set(type, level instanceof Level ? level : getLevel(level))633}634635/**636* Converts this instance to its JSON representation.637* @return {!Object<string, string>} The JSON representation of this set of638* preferences.639*/640toJSON() {641let json = {}642for (let key of this.prefs_.keys()) {643json[key] = this.prefs_.get(key).name644}645return json646}647}648649// PUBLIC API650651module.exports = {652Entry: Entry,653Level: Level,654LogManager: LogManager,655Logger: Logger,656Preferences: Preferences,657Type: Type,658addConsoleHandler: addConsoleHandler,659getLevel: getLevel,660getLogger: getLogger,661installConsoleHandler: installConsoleHandler,662removeConsoleHandler: removeConsoleHandler,663}664665666