logging.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. // Licensed to the Software Freedom Conservancy (SFC) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The SFC licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. 'use strict';
  18. /**
  19. * @fileoverview Defines WebDriver's logging system. The logging system is
  20. * broken into major components: local and remote logging.
  21. *
  22. * The local logging API, which is anchored by the {@linkplain Logger} class is
  23. * similar to Java's logging API. Loggers, retrieved by
  24. * {@linkplain #getLogger getLogger(name)}, use hierarchical, dot-delimited
  25. * namespaces (e.g. "" > "webdriver" > "webdriver.logging"). Recorded log
  26. * messages are represented by the {@linkplain Entry} class. You can capture log
  27. * records by {@linkplain Logger#addHandler attaching} a handler function to the
  28. * desired logger. For convenience, you can quickly enable logging to the
  29. * console by simply calling {@linkplain #installConsoleHandler
  30. * installConsoleHandler}.
  31. *
  32. * The [remote logging API](https://github.com/SeleniumHQ/selenium/wiki/Logging)
  33. * allows you to retrieve logs from a remote WebDriver server. This API uses the
  34. * {@link Preferences} class to define desired log levels prior to creating
  35. * a WebDriver session:
  36. *
  37. * var prefs = new logging.Preferences();
  38. * prefs.setLevel(logging.Type.BROWSER, logging.Level.DEBUG);
  39. *
  40. * var caps = Capabilities.chrome();
  41. * caps.setLoggingPrefs(prefs);
  42. * // ...
  43. *
  44. * Remote log entries, also represented by the {@link Entry} class, may be
  45. * retrieved via {@link webdriver.WebDriver.Logs}:
  46. *
  47. * driver.manage().logs().get(logging.Type.BROWSER)
  48. * .then(function(entries) {
  49. * entries.forEach(function(entry) {
  50. * console.log('[%s] %s', entry.level.name, entry.message);
  51. * });
  52. * });
  53. *
  54. * **NOTE:** Only a few browsers support the remote logging API (notably
  55. * Firefox and Chrome). Firefox supports basic logging functionality, while
  56. * Chrome exposes robust
  57. * [performance logging](https://sites.google.com/a/chromium.org/chromedriver/logging)
  58. * options. Remote logging is still considered a non-standard feature, and the
  59. * APIs exposed by this module for it are non-frozen. This module will be
  60. * updated, possibly breaking backwards-compatibility, once logging is
  61. * officially defined by the
  62. * [W3C WebDriver spec](http://www.w3.org/TR/webdriver/).
  63. */
  64. /**
  65. * Defines a message level that may be used to control logging output.
  66. *
  67. * @final
  68. */
  69. class Level {
  70. /**
  71. * @param {string} name the level's name.
  72. * @param {number} level the level's numeric value.
  73. */
  74. constructor(name, level) {
  75. if (level < 0) {
  76. throw new TypeError('Level must be >= 0');
  77. }
  78. /** @private {string} */
  79. this.name_ = name;
  80. /** @private {number} */
  81. this.value_ = level;
  82. }
  83. /** This logger's name. */
  84. get name() {
  85. return this.name_;
  86. }
  87. /** The numeric log level. */
  88. get value() {
  89. return this.value_;
  90. }
  91. /** @override */
  92. toString() {
  93. return this.name;
  94. }
  95. }
  96. /**
  97. * Indicates no log messages should be recorded.
  98. * @const
  99. */
  100. Level.OFF = new Level('OFF', Infinity);
  101. /**
  102. * Log messages with a level of `1000` or higher.
  103. * @const
  104. */
  105. Level.SEVERE = new Level('SEVERE', 1000);
  106. /**
  107. * Log messages with a level of `900` or higher.
  108. * @const
  109. */
  110. Level.WARNING = new Level('WARNING', 900);
  111. /**
  112. * Log messages with a level of `800` or higher.
  113. * @const
  114. */
  115. Level.INFO = new Level('INFO', 800);
  116. /**
  117. * Log messages with a level of `700` or higher.
  118. * @const
  119. */
  120. Level.DEBUG = new Level('DEBUG', 700);
  121. /**
  122. * Log messages with a level of `500` or higher.
  123. * @const
  124. */
  125. Level.FINE = new Level('FINE', 500);
  126. /**
  127. * Log messages with a level of `400` or higher.
  128. * @const
  129. */
  130. Level.FINER = new Level('FINER', 400);
  131. /**
  132. * Log messages with a level of `300` or higher.
  133. * @const
  134. */
  135. Level.FINEST = new Level('FINEST', 300);
  136. /**
  137. * Indicates all log messages should be recorded.
  138. * @const
  139. */
  140. Level.ALL = new Level('ALL', 0);
  141. const ALL_LEVELS = /** !Set<Level> */new Set([
  142. Level.OFF,
  143. Level.SEVERE,
  144. Level.WARNING,
  145. Level.INFO,
  146. Level.DEBUG,
  147. Level.FINE,
  148. Level.FINER,
  149. Level.FINEST,
  150. Level.ALL
  151. ]);
  152. const LEVELS_BY_NAME = /** !Map<string, !Level> */ new Map([
  153. [Level.OFF.name, Level.OFF],
  154. [Level.SEVERE.name, Level.SEVERE],
  155. [Level.WARNING.name, Level.WARNING],
  156. [Level.INFO.name, Level.INFO],
  157. [Level.DEBUG.name, Level.DEBUG],
  158. [Level.FINE.name, Level.FINE],
  159. [Level.FINER.name, Level.FINER],
  160. [Level.FINEST.name, Level.FINEST],
  161. [Level.ALL.name, Level.ALL]
  162. ]);
  163. /**
  164. * Converts a level name or value to a {@link Level} value. If the name/value
  165. * is not recognized, {@link Level.ALL} will be returned.
  166. *
  167. * @param {(number|string)} nameOrValue The log level name, or value, to
  168. * convert.
  169. * @return {!Level} The converted level.
  170. */
  171. function getLevel(nameOrValue) {
  172. if (typeof nameOrValue === 'string') {
  173. return LEVELS_BY_NAME.get(nameOrValue) || Level.ALL;
  174. }
  175. if (typeof nameOrValue !== 'number') {
  176. throw new TypeError('not a string or number');
  177. }
  178. for (let level of ALL_LEVELS) {
  179. if (nameOrValue >= level.value) {
  180. return level;
  181. }
  182. }
  183. return Level.ALL;
  184. }
  185. /**
  186. * Describes a single log entry.
  187. *
  188. * @final
  189. */
  190. class Entry {
  191. /**
  192. * @param {(!Level|string|number)} level The entry level.
  193. * @param {string} message The log message.
  194. * @param {number=} opt_timestamp The time this entry was generated, in
  195. * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the
  196. * current time will be used.
  197. * @param {string=} opt_type The log type, if known.
  198. */
  199. constructor(level, message, opt_timestamp, opt_type) {
  200. this.level = level instanceof Level ? level : getLevel(level);
  201. this.message = message;
  202. this.timestamp =
  203. typeof opt_timestamp === 'number' ? opt_timestamp : Date.now();
  204. this.type = opt_type || '';
  205. }
  206. /**
  207. * @return {{level: string, message: string, timestamp: number,
  208. * type: string}} The JSON representation of this entry.
  209. */
  210. toJSON() {
  211. return {
  212. 'level': this.level.name,
  213. 'message': this.message,
  214. 'timestamp': this.timestamp,
  215. 'type': this.type
  216. };
  217. }
  218. }
  219. /** @typedef {(string|function(): string)} */
  220. let Loggable;
  221. /**
  222. * An object used to log debugging messages. Loggers use a hierarchical,
  223. * dot-separated naming scheme. For instance, "foo" is considered the parent of
  224. * the "foo.bar" and an ancestor of "foo.bar.baz".
  225. *
  226. * Each logger may be assigned a {@linkplain #setLevel log level}, which
  227. * controls which level of messages will be reported to the
  228. * {@linkplain #addHandler handlers} attached to this instance. If a log level
  229. * is not explicitly set on a logger, it will inherit its parent.
  230. *
  231. * This class should never be directly instantiated. Instead, users should
  232. * obtain logger references using the {@linkplain ./logging.getLogger()
  233. * getLogger()} function.
  234. *
  235. * @final
  236. */
  237. class Logger {
  238. /**
  239. * @param {string} name the name of this logger.
  240. * @param {Level=} opt_level the initial level for this logger.
  241. */
  242. constructor(name, opt_level) {
  243. /** @private {string} */
  244. this.name_ = name;
  245. /** @private {Level} */
  246. this.level_ = opt_level || null;
  247. /** @private {Logger} */
  248. this.parent_ = null;
  249. /** @private {Set<function(!Entry)>} */
  250. this.handlers_ = null;
  251. }
  252. /** @return {string} the name of this logger. */
  253. getName() {
  254. return this.name_;
  255. }
  256. /**
  257. * @param {Level} level the new level for this logger, or `null` if the logger
  258. * should inherit its level from its parent logger.
  259. */
  260. setLevel(level) {
  261. this.level_ = level;
  262. }
  263. /** @return {Level} the log level for this logger. */
  264. getLevel() {
  265. return this.level_;
  266. }
  267. /**
  268. * @return {!Level} the effective level for this logger.
  269. */
  270. getEffectiveLevel() {
  271. let logger = this;
  272. let level;
  273. do {
  274. level = logger.level_;
  275. logger = logger.parent_;
  276. } while (logger && !level);
  277. return level || Level.OFF;
  278. }
  279. /**
  280. * @param {!Level} level the level to check.
  281. * @return {boolean} whether messages recorded at the given level are loggable
  282. * by this instance.
  283. */
  284. isLoggable(level) {
  285. return level.value !== Level.OFF.value
  286. && level.value >= this.getEffectiveLevel().value;
  287. }
  288. /**
  289. * Adds a handler to this logger. The handler will be invoked for each message
  290. * logged with this instance, or any of its descendants.
  291. *
  292. * @param {function(!Entry)} handler the handler to add.
  293. */
  294. addHandler(handler) {
  295. if (!this.handlers_) {
  296. this.handlers_ = new Set;
  297. }
  298. this.handlers_.add(handler);
  299. }
  300. /**
  301. * Removes a handler from this logger.
  302. *
  303. * @param {function(!Entry)} handler the handler to remove.
  304. * @return {boolean} whether a handler was successfully removed.
  305. */
  306. removeHandler(handler) {
  307. if (!this.handlers_) {
  308. return false;
  309. }
  310. return this.handlers_.delete(handler);
  311. }
  312. /**
  313. * Logs a message at the given level. The message may be defined as a string
  314. * or as a function that will return the message. If a function is provided,
  315. * it will only be invoked if this logger's
  316. * {@linkplain #getEffectiveLevel() effective log level} includes the given
  317. * `level`.
  318. *
  319. * @param {!Level} level the level at which to log the message.
  320. * @param {(string|function(): string)} loggable the message to log, or a
  321. * function that will return the message.
  322. */
  323. log(level, loggable) {
  324. if (!this.isLoggable(level)) {
  325. return;
  326. }
  327. let message = '[' + this.name_ + '] '
  328. + (typeof loggable === 'function' ? loggable() : loggable);
  329. let entry = new Entry(level, message, Date.now());
  330. for (let logger = this; !!logger; logger = logger.parent_) {
  331. if (logger.handlers_) {
  332. for (let handler of logger.handlers_) {
  333. handler(entry);
  334. }
  335. }
  336. }
  337. }
  338. /**
  339. * Logs a message at the {@link Level.SEVERE} log level.
  340. * @param {(string|function(): string)} loggable the message to log, or a
  341. * function that will return the message.
  342. */
  343. severe(loggable) {
  344. this.log(Level.SEVERE, loggable);
  345. }
  346. /**
  347. * Logs a message at the {@link Level.WARNING} log level.
  348. * @param {(string|function(): string)} loggable the message to log, or a
  349. * function that will return the message.
  350. */
  351. warning(loggable) {
  352. this.log(Level.WARNING, loggable);
  353. }
  354. /**
  355. * Logs a message at the {@link Level.INFO} log level.
  356. * @param {(string|function(): string)} loggable the message to log, or a
  357. * function that will return the message.
  358. */
  359. info(loggable) {
  360. this.log(Level.INFO, loggable);
  361. }
  362. /**
  363. * Logs a message at the {@link Level.DEBUG} log level.
  364. * @param {(string|function(): string)} loggable the message to log, or a
  365. * function that will return the message.
  366. */
  367. debug(loggable) {
  368. this.log(Level.DEBUG, loggable);
  369. }
  370. /**
  371. * Logs a message at the {@link Level.FINE} log level.
  372. * @param {(string|function(): string)} loggable the message to log, or a
  373. * function that will return the message.
  374. */
  375. fine(loggable) {
  376. this.log(Level.FINE, loggable);
  377. }
  378. /**
  379. * Logs a message at the {@link Level.FINER} log level.
  380. * @param {(string|function(): string)} loggable the message to log, or a
  381. * function that will return the message.
  382. */
  383. finer(loggable) {
  384. this.log(Level.FINER, loggable);
  385. }
  386. /**
  387. * Logs a message at the {@link Level.FINEST} log level.
  388. * @param {(string|function(): string)} loggable the message to log, or a
  389. * function that will return the message.
  390. */
  391. finest(loggable) {
  392. this.log(Level.FINEST, loggable);
  393. }
  394. }
  395. /**
  396. * Maintains a collection of loggers.
  397. *
  398. * @final
  399. */
  400. class LogManager {
  401. constructor() {
  402. /** @private {!Map<string, !Logger>} */
  403. this.loggers_ = new Map;
  404. this.root_ = new Logger('', Level.OFF);
  405. }
  406. /**
  407. * Retrieves a named logger, creating it in the process. This function will
  408. * implicitly create the requested logger, and any of its parents, if they
  409. * do not yet exist.
  410. *
  411. * @param {string} name the logger's name.
  412. * @return {!Logger} the requested logger.
  413. */
  414. getLogger(name) {
  415. if (!name) {
  416. return this.root_;
  417. }
  418. let parent = this.root_;
  419. for (let i = name.indexOf('.'); i != -1; i = name.indexOf('.', i + 1)) {
  420. let parentName = name.substr(0, i);
  421. parent = this.createLogger_(parentName, parent);
  422. }
  423. return this.createLogger_(name, parent);
  424. }
  425. /**
  426. * Creates a new logger.
  427. *
  428. * @param {string} name the logger's name.
  429. * @param {!Logger} parent the logger's parent.
  430. * @return {!Logger} the new logger.
  431. * @private
  432. */
  433. createLogger_(name, parent) {
  434. if (this.loggers_.has(name)) {
  435. return /** @type {!Logger} */(this.loggers_.get(name));
  436. }
  437. let logger = new Logger(name, null);
  438. logger.parent_ = parent;
  439. this.loggers_.set(name, logger);
  440. return logger;
  441. }
  442. }
  443. const logManager = new LogManager;
  444. /**
  445. * Retrieves a named logger, creating it in the process. This function will
  446. * implicitly create the requested logger, and any of its parents, if they
  447. * do not yet exist.
  448. *
  449. * The log level will be unspecified for newly created loggers. Use
  450. * {@link Logger#setLevel(level)} to explicitly set a level.
  451. *
  452. * @param {string} name the logger's name.
  453. * @return {!Logger} the requested logger.
  454. */
  455. function getLogger(name) {
  456. return logManager.getLogger(name);
  457. }
  458. /**
  459. * Pads a number to ensure it has a minimum of two digits.
  460. *
  461. * @param {number} n the number to be padded.
  462. * @return {string} the padded number.
  463. */
  464. function pad(n) {
  465. if (n >= 10) {
  466. return '' + n;
  467. } else {
  468. return '0' + n;
  469. }
  470. }
  471. /**
  472. * Logs all messages to the Console API.
  473. * @param {!Entry} entry the entry to log.
  474. */
  475. function consoleHandler(entry) {
  476. if (typeof console === 'undefined' || !console) {
  477. return;
  478. }
  479. var timestamp = new Date(entry.timestamp);
  480. var msg =
  481. '[' + timestamp.getUTCFullYear() + '-' +
  482. pad(timestamp.getUTCMonth() + 1) + '-' +
  483. pad(timestamp.getUTCDate()) + 'T' +
  484. pad(timestamp.getUTCHours()) + ':' +
  485. pad(timestamp.getUTCMinutes()) + ':' +
  486. pad(timestamp.getUTCSeconds()) + 'Z] ' +
  487. '[' + entry.level.name + '] ' +
  488. entry.message;
  489. var level = entry.level.value;
  490. if (level >= Level.SEVERE.value) {
  491. console.error(msg);
  492. } else if (level >= Level.WARNING.value) {
  493. console.warn(msg);
  494. } else {
  495. console.log(msg);
  496. }
  497. }
  498. /**
  499. * Adds the console handler to the given logger. The console handler will log
  500. * all messages using the JavaScript Console API.
  501. *
  502. * @param {Logger=} opt_logger The logger to add the handler to; defaults
  503. * to the root logger.
  504. */
  505. function addConsoleHandler(opt_logger) {
  506. let logger = opt_logger || logManager.root_;
  507. logger.addHandler(consoleHandler);
  508. }
  509. /**
  510. * Removes the console log handler from the given logger.
  511. *
  512. * @param {Logger=} opt_logger The logger to remove the handler from; defaults
  513. * to the root logger.
  514. * @see exports.addConsoleHandler
  515. */
  516. function removeConsoleHandler(opt_logger) {
  517. let logger = opt_logger || logManager.root_;
  518. logger.removeHandler(consoleHandler);
  519. }
  520. /**
  521. * Installs the console log handler on the root logger.
  522. */
  523. function installConsoleHandler() {
  524. addConsoleHandler(logManager.root_);
  525. }
  526. /**
  527. * Common log types.
  528. * @enum {string}
  529. */
  530. const Type = {
  531. /** Logs originating from the browser. */
  532. BROWSER: 'browser',
  533. /** Logs from a WebDriver client. */
  534. CLIENT: 'client',
  535. /** Logs from a WebDriver implementation. */
  536. DRIVER: 'driver',
  537. /** Logs related to performance. */
  538. PERFORMANCE: 'performance',
  539. /** Logs from the remote server. */
  540. SERVER: 'server'
  541. };
  542. /**
  543. * Describes the log preferences for a WebDriver session.
  544. *
  545. * @final
  546. */
  547. class Preferences {
  548. constructor() {
  549. /** @private {!Map<string, !Level>} */
  550. this.prefs_ = new Map;
  551. }
  552. /**
  553. * Sets the desired logging level for a particular log type.
  554. * @param {(string|Type)} type The log type.
  555. * @param {(!Level|string|number)} level The desired log level.
  556. * @throws {TypeError} if `type` is not a `string`.
  557. */
  558. setLevel(type, level) {
  559. if (typeof type !== 'string') {
  560. throw TypeError('specified log type is not a string: ' + typeof type);
  561. }
  562. this.prefs_.set(type, level instanceof Level ? level : getLevel(level));
  563. }
  564. /**
  565. * Converts this instance to its JSON representation.
  566. * @return {!Object<string, string>} The JSON representation of this set of
  567. * preferences.
  568. */
  569. toJSON() {
  570. let json = {};
  571. for (let key of this.prefs_.keys()) {
  572. json[key] = this.prefs_.get(key).name;
  573. }
  574. return json;
  575. }
  576. }
  577. // PUBLIC API
  578. module.exports = {
  579. Entry: Entry,
  580. Level: Level,
  581. LogManager: LogManager,
  582. Logger: Logger,
  583. Preferences: Preferences,
  584. Type: Type,
  585. addConsoleHandler: addConsoleHandler,
  586. getLevel: getLevel,
  587. getLogger: getLogger,
  588. installConsoleHandler: installConsoleHandler,
  589. removeConsoleHandler: removeConsoleHandler
  590. };