UNPKG

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