Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
seleniumhq
GitHub Repository: seleniumhq/selenium
Path: blob/trunk/javascript/selenium-webdriver/lib/logging.js
2884 views
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
*/
72
class 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
*/
109
Level.OFF = new Level('OFF', Infinity)
110
111
/**
112
* Log messages with a level of `1000` or higher.
113
* @const
114
*/
115
Level.SEVERE = new Level('SEVERE', 1000)
116
117
/**
118
* Log messages with a level of `900` or higher.
119
* @const
120
*/
121
Level.WARNING = new Level('WARNING', 900)
122
123
/**
124
* Log messages with a level of `800` or higher.
125
* @const
126
*/
127
Level.INFO = new Level('INFO', 800)
128
129
/**
130
* Log messages with a level of `700` or higher.
131
* @const
132
*/
133
Level.DEBUG = new Level('DEBUG', 700)
134
135
/**
136
* Log messages with a level of `500` or higher.
137
* @const
138
*/
139
Level.FINE = new Level('FINE', 500)
140
141
/**
142
* Log messages with a level of `400` or higher.
143
* @const
144
*/
145
Level.FINER = new Level('FINER', 400)
146
147
/**
148
* Log messages with a level of `300` or higher.
149
* @const
150
*/
151
Level.FINEST = new Level('FINEST', 300)
152
153
/**
154
* Indicates all log messages should be recorded.
155
* @const
156
*/
157
Level.ALL = new Level('ALL', 0)
158
159
const 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
171
const 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
*/
191
function 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
*/
211
class 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 = typeof opt_timestamp === 'number' ? opt_timestamp : Date.now()
224
this.type = opt_type || ''
225
}
226
227
/**
228
* @return {{level: string, message: string, timestamp: number,
229
* type: string}} The JSON representation of this entry.
230
*/
231
toJSON() {
232
return {
233
level: this.level.name,
234
message: this.message,
235
timestamp: this.timestamp,
236
type: this.type,
237
}
238
}
239
}
240
241
/**
242
* An object used to log debugging messages. Loggers use a hierarchical,
243
* dot-separated naming scheme. For instance, "foo" is considered the parent of
244
* the "foo.bar" and an ancestor of "foo.bar.baz".
245
*
246
* Each logger may be assigned a {@linkplain #setLevel log level}, which
247
* controls which level of messages will be reported to the
248
* {@linkplain #addHandler handlers} attached to this instance. If a log level
249
* is not explicitly set on a logger, it will inherit its parent.
250
*
251
* This class should never be directly instantiated. Instead, users should
252
* obtain logger references using the {@linkplain ./logging.getLogger()
253
* getLogger()} function.
254
*
255
* @final
256
*/
257
class Logger {
258
/**
259
* @param {string} name the name of this logger.
260
* @param {Level=} opt_level the initial level for this logger.
261
*/
262
constructor(name, opt_level) {
263
/** @private {string} */
264
this.name_ = name
265
266
/** @private {Level} */
267
this.level_ = opt_level || null
268
269
/** @private {Logger} */
270
this.parent_ = null
271
272
/** @private {Set<function(!Entry)>} */
273
this.handlers_ = null
274
}
275
276
/** @return {string} the name of this logger. */
277
getName() {
278
return this.name_
279
}
280
281
/**
282
* @param {Level} level the new level for this logger, or `null` if the logger
283
* should inherit its level from its parent logger.
284
*/
285
setLevel(level) {
286
this.level_ = level
287
}
288
289
/** @return {Level} the log level for this logger. */
290
getLevel() {
291
return this.level_
292
}
293
294
/**
295
* @return {!Level} the effective level for this logger.
296
*/
297
getEffectiveLevel() {
298
let logger = this
299
let level
300
do {
301
level = logger.level_
302
logger = logger.parent_
303
} while (logger && !level)
304
return level || Level.OFF
305
}
306
307
/**
308
* @param {!Level} level the level to check.
309
* @return {boolean} whether messages recorded at the given level are loggable
310
* by this instance.
311
*/
312
isLoggable(level) {
313
return level.value !== Level.OFF.value && level.value >= this.getEffectiveLevel().value
314
}
315
316
/**
317
* Adds a handler to this logger. The handler will be invoked for each message
318
* logged with this instance, or any of its descendants.
319
*
320
* @param {function(!Entry)} handler the handler to add.
321
*/
322
addHandler(handler) {
323
if (!this.handlers_) {
324
this.handlers_ = new Set()
325
}
326
this.handlers_.add(handler)
327
}
328
329
/**
330
* Removes a handler from this logger.
331
*
332
* @param {function(!Entry)} handler the handler to remove.
333
* @return {boolean} whether a handler was successfully removed.
334
*/
335
removeHandler(handler) {
336
if (!this.handlers_) {
337
return false
338
}
339
return this.handlers_.delete(handler)
340
}
341
342
/**
343
* Logs a message at the given level. The message may be defined as a string
344
* or as a function that will return the message. If a function is provided,
345
* it will only be invoked if this logger's
346
* {@linkplain #getEffectiveLevel() effective log level} includes the given
347
* `level`.
348
*
349
* @param {!Level} level the level at which to log the message.
350
* @param {(string|function(): string)} loggable the message to log, or a
351
* function that will return the message.
352
*/
353
log(level, loggable) {
354
if (!this.isLoggable(level)) {
355
return
356
}
357
let message = '[' + this.name_ + '] ' + (typeof loggable === 'function' ? loggable() : loggable)
358
let entry = new Entry(level, message, Date.now())
359
for (let logger = this; logger; logger = logger.parent_) {
360
if (logger.handlers_) {
361
for (let handler of logger.handlers_) {
362
handler(entry)
363
}
364
}
365
}
366
}
367
368
/**
369
* Logs a message at the {@link Level.SEVERE} log level.
370
* @param {(string|function(): string)} loggable the message to log, or a
371
* function that will return the message.
372
*/
373
severe(loggable) {
374
this.log(Level.SEVERE, loggable)
375
}
376
377
/**
378
* Logs a message at the {@link Level.WARNING} log level.
379
* @param {(string|function(): string)} loggable the message to log, or a
380
* function that will return the message.
381
*/
382
warning(loggable) {
383
this.log(Level.WARNING, loggable)
384
}
385
386
/**
387
* Logs a message at the {@link Level.INFO} log level.
388
* @param {(string|function(): string)} loggable the message to log, or a
389
* function that will return the message.
390
*/
391
info(loggable) {
392
this.log(Level.INFO, loggable)
393
}
394
395
/**
396
* Logs a message at the {@link Level.DEBUG} log level.
397
* @param {(string|function(): string)} loggable the message to log, or a
398
* function that will return the message.
399
*/
400
debug(loggable) {
401
this.log(Level.DEBUG, loggable)
402
}
403
404
/**
405
* Logs a message at the {@link Level.FINE} log level.
406
* @param {(string|function(): string)} loggable the message to log, or a
407
* function that will return the message.
408
*/
409
fine(loggable) {
410
this.log(Level.FINE, loggable)
411
}
412
413
/**
414
* Logs a message at the {@link Level.FINER} log level.
415
* @param {(string|function(): string)} loggable the message to log, or a
416
* function that will return the message.
417
*/
418
finer(loggable) {
419
this.log(Level.FINER, loggable)
420
}
421
422
/**
423
* Logs a message at the {@link Level.FINEST} log level.
424
* @param {(string|function(): string)} loggable the message to log, or a
425
* function that will return the message.
426
*/
427
finest(loggable) {
428
this.log(Level.FINEST, loggable)
429
}
430
}
431
432
/**
433
* Maintains a collection of loggers.
434
*
435
* @final
436
*/
437
class LogManager {
438
constructor() {
439
/** @private {!Map<string, !Logger>} */
440
this.loggers_ = new Map()
441
this.root_ = new Logger('', Level.OFF)
442
}
443
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
* @param {string} name the logger's name.
450
* @return {!Logger} the requested logger.
451
*/
452
getLogger(name) {
453
if (!name) {
454
return this.root_
455
}
456
let parent = this.root_
457
for (let i = name.indexOf('.'); i != -1; i = name.indexOf('.', i + 1)) {
458
let parentName = name.substr(0, i)
459
parent = this.createLogger_(parentName, parent)
460
}
461
return this.createLogger_(name, parent)
462
}
463
464
/**
465
* Creates a new logger.
466
*
467
* @param {string} name the logger's name.
468
* @param {!Logger} parent the logger's parent.
469
* @return {!Logger} the new logger.
470
* @private
471
*/
472
createLogger_(name, parent) {
473
if (this.loggers_.has(name)) {
474
return /** @type {!Logger} */ (this.loggers_.get(name))
475
}
476
let logger = new Logger(name, null)
477
logger.parent_ = parent
478
this.loggers_.set(name, logger)
479
return logger
480
}
481
}
482
483
const logManager = new LogManager()
484
485
/**
486
* Retrieves a named logger, creating it in the process. This function will
487
* implicitly create the requested logger, and any of its parents, if they
488
* do not yet exist.
489
*
490
* The log level will be unspecified for newly created loggers. Use
491
* {@link Logger#setLevel(level)} to explicitly set a level.
492
*
493
* @param {string} name the logger's name.
494
* @return {!Logger} the requested logger.
495
*/
496
function getLogger(name) {
497
return logManager.getLogger(name)
498
}
499
500
/**
501
* Pads a number to ensure it has a minimum of two digits.
502
*
503
* @param {number} n the number to be padded.
504
* @return {string} the padded number.
505
*/
506
function pad(n) {
507
if (n >= 10) {
508
return '' + n
509
} else {
510
return '0' + n
511
}
512
}
513
514
/**
515
* Logs all messages to the Console API.
516
* @param {!Entry} entry the entry to log.
517
*/
518
function consoleHandler(entry) {
519
if (typeof console === 'undefined' || !console) {
520
return
521
}
522
523
var timestamp = new Date(entry.timestamp)
524
var msg =
525
'[' +
526
timestamp.getUTCFullYear() +
527
'-' +
528
pad(timestamp.getUTCMonth() + 1) +
529
'-' +
530
pad(timestamp.getUTCDate()) +
531
'T' +
532
pad(timestamp.getUTCHours()) +
533
':' +
534
pad(timestamp.getUTCMinutes()) +
535
':' +
536
pad(timestamp.getUTCSeconds()) +
537
'Z] ' +
538
'[' +
539
entry.level.name +
540
'] ' +
541
entry.message
542
543
var level = entry.level.value
544
if (level >= Level.SEVERE.value) {
545
console.error(msg)
546
} else if (level >= Level.WARNING.value) {
547
console.warn(msg)
548
} else {
549
console.log(msg)
550
}
551
}
552
553
/**
554
* Adds the console handler to the given logger. The console handler will log
555
* all messages using the JavaScript Console API.
556
*
557
* @param {Logger=} opt_logger The logger to add the handler to; defaults
558
* to the root logger.
559
*/
560
function addConsoleHandler(opt_logger) {
561
let logger = opt_logger || logManager.root_
562
logger.addHandler(consoleHandler)
563
}
564
565
/**
566
* Removes the console log handler from the given logger.
567
*
568
* @param {Logger=} opt_logger The logger to remove the handler from; defaults
569
* to the root logger.
570
* @see exports.addConsoleHandler
571
*/
572
function removeConsoleHandler(opt_logger) {
573
let logger = opt_logger || logManager.root_
574
logger.removeHandler(consoleHandler)
575
}
576
577
/**
578
* Installs the console log handler on the root logger.
579
*/
580
function installConsoleHandler() {
581
addConsoleHandler(logManager.root_)
582
}
583
584
/**
585
* Common log types.
586
* @enum {string}
587
*/
588
const Type = {
589
/** Logs originating from the browser. */
590
BROWSER: 'browser',
591
/** Logs from a WebDriver client. */
592
CLIENT: 'client',
593
/** Logs from a WebDriver implementation. */
594
DRIVER: 'driver',
595
/** Logs related to performance. */
596
PERFORMANCE: 'performance',
597
/** Logs from the remote server. */
598
SERVER: 'server',
599
}
600
601
/**
602
* Describes the log preferences for a WebDriver session.
603
*
604
* @final
605
*/
606
class Preferences {
607
constructor() {
608
/** @private {!Map<string, !Level>} */
609
this.prefs_ = new Map()
610
}
611
612
/**
613
* Sets the desired logging level for a particular log type.
614
* @param {(string|Type)} type The log type.
615
* @param {(!Level|string|number)} level The desired log level.
616
* @throws {TypeError} if `type` is not a `string`.
617
*/
618
setLevel(type, level) {
619
if (typeof type !== 'string') {
620
throw TypeError('specified log type is not a string: ' + typeof type)
621
}
622
this.prefs_.set(type, level instanceof Level ? level : getLevel(level))
623
}
624
625
/**
626
* Converts this instance to its JSON representation.
627
* @return {!Object<string, string>} The JSON representation of this set of
628
* preferences.
629
*/
630
toJSON() {
631
let json = {}
632
for (let key of this.prefs_.keys()) {
633
json[key] = this.prefs_.get(key).name
634
}
635
return json
636
}
637
}
638
639
// PUBLIC API
640
641
module.exports = {
642
Entry: Entry,
643
Level: Level,
644
LogManager: LogManager,
645
Logger: Logger,
646
Preferences: Preferences,
647
Type: Type,
648
addConsoleHandler: addConsoleHandler,
649
getLevel: getLevel,
650
getLogger: getLogger,
651
installConsoleHandler: installConsoleHandler,
652
removeConsoleHandler: removeConsoleHandler,
653
}
654
655