Path: blob/trunk/javascript/selenium-webdriver/lib/logging.js
2884 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/**485* Retrieves a named logger, creating it in the process. This function will486* implicitly create the requested logger, and any of its parents, if they487* do not yet exist.488*489* The log level will be unspecified for newly created loggers. Use490* {@link Logger#setLevel(level)} to explicitly set a level.491*492* @param {string} name the logger's name.493* @return {!Logger} the requested logger.494*/495function getLogger(name) {496return logManager.getLogger(name)497}498499/**500* Pads a number to ensure it has a minimum of two digits.501*502* @param {number} n the number to be padded.503* @return {string} the padded number.504*/505function pad(n) {506if (n >= 10) {507return '' + n508} else {509return '0' + n510}511}512513/**514* Logs all messages to the Console API.515* @param {!Entry} entry the entry to log.516*/517function consoleHandler(entry) {518if (typeof console === 'undefined' || !console) {519return520}521522var timestamp = new Date(entry.timestamp)523var msg =524'[' +525timestamp.getUTCFullYear() +526'-' +527pad(timestamp.getUTCMonth() + 1) +528'-' +529pad(timestamp.getUTCDate()) +530'T' +531pad(timestamp.getUTCHours()) +532':' +533pad(timestamp.getUTCMinutes()) +534':' +535pad(timestamp.getUTCSeconds()) +536'Z] ' +537'[' +538entry.level.name +539'] ' +540entry.message541542var level = entry.level.value543if (level >= Level.SEVERE.value) {544console.error(msg)545} else if (level >= Level.WARNING.value) {546console.warn(msg)547} else {548console.log(msg)549}550}551552/**553* Adds the console handler to the given logger. The console handler will log554* all messages using the JavaScript Console API.555*556* @param {Logger=} opt_logger The logger to add the handler to; defaults557* to the root logger.558*/559function addConsoleHandler(opt_logger) {560let logger = opt_logger || logManager.root_561logger.addHandler(consoleHandler)562}563564/**565* Removes the console log handler from the given logger.566*567* @param {Logger=} opt_logger The logger to remove the handler from; defaults568* to the root logger.569* @see exports.addConsoleHandler570*/571function removeConsoleHandler(opt_logger) {572let logger = opt_logger || logManager.root_573logger.removeHandler(consoleHandler)574}575576/**577* Installs the console log handler on the root logger.578*/579function installConsoleHandler() {580addConsoleHandler(logManager.root_)581}582583/**584* Common log types.585* @enum {string}586*/587const Type = {588/** Logs originating from the browser. */589BROWSER: 'browser',590/** Logs from a WebDriver client. */591CLIENT: 'client',592/** Logs from a WebDriver implementation. */593DRIVER: 'driver',594/** Logs related to performance. */595PERFORMANCE: 'performance',596/** Logs from the remote server. */597SERVER: 'server',598}599600/**601* Describes the log preferences for a WebDriver session.602*603* @final604*/605class Preferences {606constructor() {607/** @private {!Map<string, !Level>} */608this.prefs_ = new Map()609}610611/**612* Sets the desired logging level for a particular log type.613* @param {(string|Type)} type The log type.614* @param {(!Level|string|number)} level The desired log level.615* @throws {TypeError} if `type` is not a `string`.616*/617setLevel(type, level) {618if (typeof type !== 'string') {619throw TypeError('specified log type is not a string: ' + typeof type)620}621this.prefs_.set(type, level instanceof Level ? level : getLevel(level))622}623624/**625* Converts this instance to its JSON representation.626* @return {!Object<string, string>} The JSON representation of this set of627* preferences.628*/629toJSON() {630let json = {}631for (let key of this.prefs_.keys()) {632json[key] = this.prefs_.get(key).name633}634return json635}636}637638// PUBLIC API639640module.exports = {641Entry: Entry,642Level: Level,643LogManager: LogManager,644Logger: Logger,645Preferences: Preferences,646Type: Type,647addConsoleHandler: addConsoleHandler,648getLevel: getLevel,649getLogger: getLogger,650installConsoleHandler: installConsoleHandler,651removeConsoleHandler: removeConsoleHandler,652}653654655