@percy/logger 1.0.0-beta.8 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,58 +1,93 @@
1
1
  # @percy/logger
2
2
 
3
- Common [winston](https://github.com/winstonjs/winston) logger used throughout the Percy CLI.
3
+ Common logger used throughout the Percy CLI and SDKs.
4
+
5
+ - [Usage](#usage)
6
+ - [`logger()`](#loggerdebug)
7
+ - [`logger.loglevel()`](#loggerloglevel)
8
+ - [`logger.format()`](#loggerformat)
9
+ - [`logger.query()`](#loggerquery)
4
10
 
5
11
  ## Usage
6
12
 
7
13
  ``` js
8
- import log from '@percy/logger'
14
+ import logger from '@percy/logger'
15
+
16
+ const log = logger('foobar')
9
17
 
10
18
  log.info('info message')
11
19
  log.error('error message')
12
20
  log.warn('warning message')
13
21
  log.debug('debug message')
22
+ log.deprecated('deprecation message')
23
+ ```
24
+
25
+ ### `logger([debug])`
26
+
27
+ Creates a group of logging functions that will be associated with the provided `debug` label. When
28
+ debug logging is enabled, this label is printed with the `[percy:*]` label and can be filtered via
29
+ the `PERCY_DEBUG` environment variable.
30
+
31
+ ``` js
32
+ PERCY_DEBUG="one:*,*:a,-*:b"
33
+
34
+ logger.loglevel('debug')
35
+
36
+ logger('one').debug('test')
37
+ logger('one:a').debug('test')
38
+ logger('one:b').debug('test')
39
+ logger('one:c').debug('test')
40
+ logger('two').debug('test')
41
+ logger('two:a').debug('test')
42
+
43
+ // only logs from the matching debug string are printed
44
+ //=> [percy:one] test
45
+ //=> [percy:one:a] test
46
+ //=> [percy:one:c] test
47
+ //=> [percy:two:a] test
14
48
  ```
15
49
 
16
- ### `#loglevel([level][, flags])`
50
+ ### `logger.loglevel([level][, flags])`
17
51
 
18
- Sets or retrieves the log level of the console transport. If the second argument is provided,
19
- `level` is treated as a fallback when all logging flags are `false`. When no arguments are provided,
20
- the method will return the current log level of the console transport.
52
+ Sets or retrieves the log level of the shared logger. If the second argument is provided, `level` is
53
+ treated as a fallback when all logging flags are `false`. When no arguments are provided, the method
54
+ will return the current log level of the shared logger.
21
55
 
22
56
  ``` js
23
- log.loglevel('info', { verbose: true })
24
- log.loglevel() === 'debug'
57
+ logger.loglevel('info', { verbose: true })
58
+ logger.loglevel() === 'debug'
25
59
 
26
- log.loglevel('info', { quiet: true })
27
- log.loglevel() === 'warn'
60
+ logger.loglevel('info', { quiet: true })
61
+ logger.loglevel() === 'warn'
28
62
 
29
- log.loglevel('info', { silent: true })
30
- log.loglevel() === 'silent'
63
+ logger.loglevel('info', { silent: true })
64
+ logget.loglevel() === 'silent'
31
65
 
32
- log.loglevel('info')
33
- log.loglevel() === 'info'
66
+ logger.loglevel('info')
67
+ logger.loglevel() === 'info'
34
68
  ```
35
69
 
36
- ### `#error(errorOrMessage)`
70
+ ### `logger.format(message, debug[, level])`
37
71
 
38
- Patched `#error()` method that handles `Error` instance's and similar error objects. When
39
- `#loglevel()` is equal to `debug`, the `Error` instance's stack trace is logged.
72
+ Returns a formatted `message` depending on the provided level and logger's own log level. When
73
+ debugging, the `debug` label is added to the prepended `[percy:*]` label.
40
74
 
41
75
  ``` js
42
- log.loglevel('debug')
43
- log.error(new Error('example'))
44
- // [percy] Error: example
45
- // at example:2:10
46
- // ...
76
+ logger.format('foobar', 'test')
77
+ //=> [percy] foobar
78
+
79
+ logger.loglevel('debug')
80
+ logger.format('foobar', 'test', warn')
81
+ //=> [percy:test] foobar (yellow for warnings)
47
82
  ```
48
83
 
49
- ### `#query(options)`
84
+ ### `logger.query(filter)`
50
85
 
51
- Patched `#query()` method that is promisified and allows a `filter` function option.
86
+ Returns an array of logs matching the provided filter function.
52
87
 
53
88
  ``` js
54
- let logs = await log.query({
55
- filter: log => true
56
- // ...other query options (see winston docs)
89
+ let logs = logger.query(log => {
90
+ return log.level === 'debug' &&
91
+ log.message.match(/foobar/)
57
92
  })
58
93
  ```
@@ -0,0 +1,19 @@
1
+ import { ANSI_COLORS, ANSI_REG } from './utils.js';
2
+ import PercyLogger from './logger.js';
3
+ export class PercyBrowserLogger extends PercyLogger {
4
+ write(level, message) {
5
+ let out = ['warn', 'error'].includes(level) ? level : 'log';
6
+ let colors = [];
7
+ message = message.replace(ANSI_REG, (_, ansi) => {
8
+ colors.push(`color:${ANSI_COLORS[ansi] || 'inherit'}`);
9
+ return '%c';
10
+ });
11
+ console[out](message, ...colors);
12
+ }
13
+
14
+ progress() {
15
+ console.error('The log.progress() method is not supported in browsers');
16
+ }
17
+
18
+ }
19
+ export default PercyBrowserLogger;
package/dist/bundle.js ADDED
@@ -0,0 +1,445 @@
1
+ (function() {
2
+ (function (exports) {
3
+ 'use strict';
4
+
5
+ const process = (typeof globalThis !== "undefined" && globalThis.process) || {};
6
+ process.env = process.env || {};
7
+ process.env.__PERCY_BROWSERIFIED__ = true;
8
+
9
+ const {
10
+ assign,
11
+ entries
12
+ } = Object; // matches ansi escape sequences
13
+
14
+ const ANSI_REG = new RegExp('[\\u001B\\u009B][[\\]()#;?]*((?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)' + '|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))', 'g'); // color names by ansi escape code
15
+
16
+ const ANSI_COLORS = {
17
+ '91m': 'red',
18
+ '32m': 'green',
19
+ '93m': 'yellow',
20
+ '34m': 'blue',
21
+ '95m': 'magenta',
22
+ '90m': 'grey'
23
+ }; // colorize each line of a string using an ansi escape sequence
24
+
25
+ const LINE_REG = /^.*$/gm;
26
+
27
+ function colorize(code, str) {
28
+ return str.replace(LINE_REG, line => `\u001b[${code}${line}\u001b[39m`);
29
+ } // map ansi colors to bound colorize functions
30
+
31
+
32
+ const colors = entries(ANSI_COLORS).reduce((colors, _ref) => {
33
+ let [code, name] = _ref;
34
+ return assign(colors, {
35
+ [name]: colorize.bind(null, code)
36
+ });
37
+ }, {});
38
+
39
+ function _defineProperty(obj, key, value) {
40
+ if (key in obj) {
41
+ Object.defineProperty(obj, key, {
42
+ value: value,
43
+ enumerable: true,
44
+ configurable: true,
45
+ writable: true
46
+ });
47
+ } else {
48
+ obj[key] = value;
49
+ }
50
+
51
+ return obj;
52
+ }
53
+
54
+ const URL_REGEXP = /\bhttps?:\/\/[^\s/$.?#].[^\s]*\b/i;
55
+ const LOG_LEVELS = {
56
+ debug: 0,
57
+ info: 1,
58
+ warn: 2,
59
+ error: 3
60
+ }; // A PercyLogger instance retains logs in-memory for quick lookups while also writing log
61
+ // messages to stdout and stderr depending on the log level and debug string.
62
+
63
+ class PercyLogger {
64
+ // default log level
65
+ // namespace regular expressions used to determine which debug logs to write
66
+ // in-memory store for logs and meta info
67
+ // track deprecations to limit noisy logging
68
+ // static vars can be overriden for testing
69
+ // Handles setting env var values and returns a singleton
70
+ constructor() {
71
+ _defineProperty(this, "level", 'info');
72
+
73
+ _defineProperty(this, "namespaces", {
74
+ include: [/^.*?$/],
75
+ exclude: []
76
+ });
77
+
78
+ _defineProperty(this, "messages", new Set());
79
+
80
+ _defineProperty(this, "deprecations", new Set());
81
+
82
+ let {
83
+ instance = this
84
+ } = this.constructor;
85
+
86
+ if (process.env.PERCY_DEBUG) {
87
+ instance.debug(process.env.PERCY_DEBUG);
88
+ } else if (process.env.PERCY_LOGLEVEL) {
89
+ instance.loglevel(process.env.PERCY_LOGLEVEL);
90
+ }
91
+
92
+ this.constructor.instance = instance;
93
+ return instance;
94
+ } // Change log level at any time or return the current log level
95
+
96
+
97
+ loglevel(level) {
98
+ if (level) this.level = level;
99
+ return this.level;
100
+ } // Change namespaces by generating an array of namespace regular expressions from a
101
+ // comma separated debug string
102
+
103
+
104
+ debug(namespaces) {
105
+ if (this.namespaces.string === namespaces) return;
106
+ this.namespaces.string = namespaces;
107
+ namespaces = namespaces.split(/[\s,]+/).filter(Boolean);
108
+ if (!namespaces.length) return this.namespaces;
109
+ this.loglevel('debug');
110
+ this.namespaces = namespaces.reduce((namespaces, ns) => {
111
+ ns = ns.replace(/:?\*/g, m => m[0] === ':' ? ':?.*?' : '.*?');
112
+
113
+ if (ns[0] === '-') {
114
+ namespaces.exclude.push(new RegExp('^' + ns.substr(1) + '$'));
115
+ } else {
116
+ namespaces.include.push(new RegExp('^' + ns + '$'));
117
+ }
118
+
119
+ return namespaces;
120
+ }, {
121
+ string: namespaces,
122
+ include: [],
123
+ exclude: []
124
+ });
125
+ } // Creates a new log group and returns level specific functions for logging
126
+
127
+
128
+ group(name) {
129
+ return Object.keys(LOG_LEVELS).reduce((group, level) => Object.assign(group, {
130
+ [level]: this.log.bind(this, name, level)
131
+ }), {
132
+ deprecated: this.deprecated.bind(this, name),
133
+ shouldLog: this.shouldLog.bind(this, name),
134
+ progress: this.progress.bind(this, name),
135
+ format: this.format.bind(this, name),
136
+ loglevel: this.loglevel.bind(this),
137
+ stdout: this.constructor.stdout,
138
+ stderr: this.constructor.stderr
139
+ });
140
+ } // Query for a set of logs by filtering the in-memory store
141
+
142
+
143
+ query(filter) {
144
+ return Array.from(this.messages).filter(filter);
145
+ } // Formats messages before they are logged to stdio
146
+
147
+
148
+ format(debug, level, message, elapsed) {
149
+ let label = 'percy';
150
+ let suffix = '';
151
+
152
+ if (arguments.length === 1) {
153
+ // format(message)
154
+ [debug, message] = [null, debug];
155
+ } else if (arguments.length === 2) {
156
+ // format(debug, message)
157
+ [level, message] = [null, level];
158
+ }
159
+
160
+ if (this.level === 'debug') {
161
+ // include debug info in the label
162
+ if (debug) label += `:${debug}`; // include elapsed time since last log
163
+
164
+ if (elapsed != null) {
165
+ suffix = ' ' + colors.grey(`(${elapsed}ms)`);
166
+ }
167
+ }
168
+
169
+ label = colors.magenta(label);
170
+
171
+ if (level === 'error') {
172
+ // red errors
173
+ message = colors.red(message);
174
+ } else if (level === 'warn') {
175
+ // yellow warnings
176
+ message = colors.yellow(message);
177
+ } else if (level === 'info' || level === 'debug') {
178
+ // blue info and debug URLs
179
+ message = message.replace(URL_REGEXP, colors.blue('$&'));
180
+ }
181
+
182
+ return `[${label}] ${message}${suffix}`;
183
+ } // Replaces the current line with a log message
184
+
185
+
186
+ progress(debug, message, persist) {
187
+ if (!this.shouldLog(debug, 'info')) return;
188
+ let {
189
+ stdout
190
+ } = this.constructor;
191
+
192
+ if (stdout.isTTY || !this._progress) {
193
+ message && (message = this.format(debug, message));
194
+ if (stdout.isTTY) stdout.cursorTo(0);else message && (message = message + '\n');
195
+ if (message) stdout.write(message);
196
+ if (stdout.isTTY) stdout.clearLine(1);
197
+ }
198
+
199
+ this._progress = !!message && {
200
+ message,
201
+ persist
202
+ };
203
+ } // Returns true or false if the level and debug group can write messages to stdio
204
+
205
+
206
+ shouldLog(debug, level) {
207
+ return LOG_LEVELS[level] != null && LOG_LEVELS[level] >= LOG_LEVELS[this.level] && !this.namespaces.exclude.some(ns => ns.test(debug)) && this.namespaces.include.some(ns => ns.test(debug));
208
+ } // Ensures that deprecation messages are not logged more than once
209
+
210
+
211
+ deprecated(debug, message, meta) {
212
+ if (this.deprecations.has(message)) return;
213
+ this.deprecations.add(message);
214
+ this.log(debug, 'warn', `Warning: ${message}`, meta);
215
+ } // Returns true if a socket is present and ready
216
+
217
+
218
+ get isRemote() {
219
+ var _this$socket;
220
+
221
+ return ((_this$socket = this.socket) === null || _this$socket === void 0 ? void 0 : _this$socket.readyState) === 1;
222
+ } // Generic log method accepts a debug group, log level, log message, and optional meta
223
+ // information to store with the message and other info
224
+
225
+
226
+ log(debug, level, message) {
227
+ let meta = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
228
+ // message might be an error object
229
+ let isError = typeof message !== 'string' && (level === 'error' || level === 'debug');
230
+ let error = isError && message; // if remote, send logs there
231
+
232
+ if (this.isRemote) {
233
+ // serialize error messages
234
+ message = isError && 'stack' in error ? {
235
+ message: error.message,
236
+ stack: error.stack
237
+ } : message;
238
+ return this.socket.send(JSON.stringify({
239
+ log: [debug, level, message, {
240
+ remote: true,
241
+ ...meta
242
+ }]
243
+ }));
244
+ } // ensure the message is a string
245
+
246
+
247
+ message = isError && message.stack || message.message || message.toString(); // timestamp each log
248
+
249
+ let timestamp = Date.now();
250
+ let entry = {
251
+ debug,
252
+ level,
253
+ message,
254
+ meta,
255
+ timestamp
256
+ };
257
+ this.messages.add(entry); // maybe write the message to stdio
258
+
259
+ if (this.shouldLog(debug, level)) {
260
+ let elapsed = timestamp - (this.lastlog || timestamp);
261
+ if (isError && this.level !== 'debug') message = error.toString();
262
+ this.write(level, this.format(debug, error ? 'error' : level, message, elapsed));
263
+ this.lastlog = timestamp;
264
+ }
265
+ } // Writes a message to stdio based on the loglevel
266
+
267
+
268
+ write(level, message) {
269
+ var _this$_progress;
270
+
271
+ let {
272
+ stdout,
273
+ stderr
274
+ } = this.constructor;
275
+ let progress = stdout.isTTY && this._progress;
276
+
277
+ if (progress) {
278
+ stdout.cursorTo(0);
279
+ stdout.clearLine();
280
+ }
281
+
282
+ (level === 'info' ? stdout : stderr).write(message + '\n');
283
+ if (!((_this$_progress = this._progress) !== null && _this$_progress !== void 0 && _this$_progress.persist)) delete this._progress;else if (progress) stdout.write(progress.message);
284
+ } // Opens a socket logging connection
285
+
286
+
287
+ connect(socket) {
288
+ // send logging environment info
289
+ let PERCY_DEBUG = process.env.PERCY_DEBUG;
290
+ let PERCY_LOGLEVEL = process.env.PERCY_LOGLEVEL || this.loglevel();
291
+ socket.send(JSON.stringify({
292
+ env: {
293
+ PERCY_DEBUG,
294
+ PERCY_LOGLEVEL
295
+ }
296
+ })); // attach remote logging handler
297
+
298
+ socket.onmessage = _ref => {
299
+ let {
300
+ data
301
+ } = _ref;
302
+ let {
303
+ log,
304
+ logAll
305
+ } = JSON.parse(data);
306
+ if (logAll) logAll.forEach(e => this.messages.add(e));
307
+ if (log) this.log(...log);
308
+ }; // return a cleanup function
309
+
310
+
311
+ return () => {
312
+ socket.onmessage = null;
313
+ };
314
+ } // Connects to a remote logger
315
+
316
+
317
+ async remote(createSocket) {
318
+ let timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
319
+ if (this.isRemote) return; // if not already connected, wait until the timeout
320
+
321
+ let err = await new Promise(resolve => {
322
+ let done = event => {
323
+ if (timeoutid == null) return;
324
+ timeoutid = clearTimeout(timeoutid);
325
+ if (this.socket) this.socket.onopen = this.socket.onerror = null;
326
+ resolve((event === null || event === void 0 ? void 0 : event.error) || (event === null || event === void 0 ? void 0 : event.type) === 'error' && 'Error: Socket connection failed');
327
+ };
328
+
329
+ let timeoutid = setTimeout(done, timeout, {
330
+ error: 'Error: Socket connection timed out'
331
+ });
332
+ Promise.resolve().then(async () => {
333
+ this.socket = await createSocket();
334
+ if (this.isRemote) return done();
335
+ this.socket.onopen = this.socket.onerror = done;
336
+ }).catch(error => done({
337
+ error
338
+ }));
339
+ }); // there was an error connecting, will fallback to normal logging
340
+
341
+ if (err) {
342
+ this.log('logger', 'debug', 'Unable to connect to remote logger');
343
+ this.log('logger', 'debug', err);
344
+ return;
345
+ } // send any messages already logged in this environment
346
+
347
+
348
+ if (this.messages.size) {
349
+ this.socket.send(JSON.stringify({
350
+ logAll: Array.from(this.messages).map(entry => ({ ...entry,
351
+ meta: {
352
+ remote: true,
353
+ ...entry.meta
354
+ }
355
+ }))
356
+ }));
357
+ } // attach an incoming message handler
358
+
359
+
360
+ this.socket.onmessage = _ref2 => {
361
+ let {
362
+ data
363
+ } = _ref2;
364
+ let {
365
+ env
366
+ } = JSON.parse(data); // update local environment info
367
+
368
+ if (env) Object.assign(process.env, env);
369
+ }; // return a cleanup function
370
+
371
+
372
+ return () => {
373
+ this.socket.onmessage = null;
374
+ this.socket = null;
375
+ };
376
+ }
377
+
378
+ }
379
+
380
+ _defineProperty(PercyLogger, "stdout", process.stdout);
381
+
382
+ _defineProperty(PercyLogger, "stderr", process.stderr);
383
+
384
+ class PercyBrowserLogger extends PercyLogger {
385
+ write(level, message) {
386
+ let out = ['warn', 'error'].includes(level) ? level : 'log';
387
+ let colors = [];
388
+ message = message.replace(ANSI_REG, (_, ansi) => {
389
+ colors.push(`color:${ANSI_COLORS[ansi] || 'inherit'}`);
390
+ return '%c';
391
+ });
392
+ console[out](message, ...colors);
393
+ }
394
+
395
+ progress() {
396
+ console.error('The log.progress() method is not supported in browsers');
397
+ }
398
+
399
+ }
400
+
401
+ function logger(name) {
402
+ return new PercyBrowserLogger().group(name);
403
+ }
404
+ Object.assign(logger, {
405
+ format: function () {
406
+ return new PercyBrowserLogger().format(...arguments);
407
+ },
408
+ query: function () {
409
+ return new PercyBrowserLogger().query(...arguments);
410
+ },
411
+ connect: function () {
412
+ return new PercyBrowserLogger().connect(...arguments);
413
+ },
414
+ remote: function () {
415
+ return new PercyBrowserLogger().remote(...arguments);
416
+ },
417
+ loglevel: function () {
418
+ return new PercyBrowserLogger().loglevel(...arguments);
419
+ }
420
+ });
421
+ Object.defineProperties(logger, {
422
+ Logger: {
423
+ get: () => PercyBrowserLogger
424
+ },
425
+ stdout: {
426
+ get: () => PercyBrowserLogger.stdout
427
+ },
428
+ stderr: {
429
+ get: () => PercyBrowserLogger.stderr
430
+ }
431
+ });
432
+
433
+ exports["default"] = logger;
434
+ exports.logger = logger;
435
+
436
+ Object.defineProperty(exports, '__esModule', { value: true });
437
+
438
+ })(this.PercyLogger = this.PercyLogger || {});
439
+ }).call(window);
440
+
441
+ if (typeof define === "function" && define.amd) {
442
+ define([], () => window.PercyLogger);
443
+ } else if (typeof module === "object" && module.exports) {
444
+ module.exports = window.PercyLogger;
445
+ }
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ import Logger from '#logger';
2
+ export function logger(name) {
3
+ return new Logger().group(name);
4
+ }
5
+ Object.assign(logger, {
6
+ format: (...args) => new Logger().format(...args),
7
+ query: (...args) => new Logger().query(...args),
8
+ connect: (...args) => new Logger().connect(...args),
9
+ remote: (...args) => new Logger().remote(...args),
10
+ loglevel: (...args) => new Logger().loglevel(...args)
11
+ });
12
+ Object.defineProperties(logger, {
13
+ Logger: {
14
+ get: () => Logger
15
+ },
16
+ stdout: {
17
+ get: () => Logger.stdout
18
+ },
19
+ stderr: {
20
+ get: () => Logger.stderr
21
+ }
22
+ });
23
+ export default logger;