-
Notifications
You must be signed in to change notification settings - Fork 0
/
logbook.js
479 lines (427 loc) · 13.5 KB
/
logbook.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
// @ts-nocheck
'use strict'
/**
* Name: Logbook JS - Console Logging Utility
* Author: Bjornar Egede-Nissen
* License: MIT
* Version: 1.0.0
* Date: 2021-12-12
*
* ### INFO ###
* Logbook is a utility for creating custom console logging functions.
*
* Features:
* - Create unlimited logging functions, all attached to console
* - Preserves call location (file, line numbers)
* - Create different log styles with CSS (background, foreground, font size, etc)
* - Filter which log messages to print to console
* - Expose console logging functions as globals (optional)
* - Compatible with both Typescript and vanilla Javascript
*
*
* ### HOW TO USE ###
*
* ~ Browser ~
* `<script src="logger.js"></script>`
*
* ~ node ~
* `import * as Loggers from 'loggers.js'`
*
* === Initializing ===
*
* `const logger = Loggers()`
* `const { log, error, warn } = logger.export()`
*
* === Further usage instructions ===
* See JSDoc attached to `Loggers()` function or output of `help()`.
*
* === Enable intellisense ===
*
* ~ Typescript ~
* Includes Typescript d.ts typings for default logger functions.
*
* ~ eslint ~
* To enable default global functions, use the included .eslintrc as a plugin.
*
* === Logger methods ===
*
* `register()` Create new logger or edit an existing one.
* `help()` Print settings and configured loggers to console.
* `setLevel()` Change the logging level.
*
*/
// === Internal types ===
/** @typedef {string|number|boolean} primitive string|number|boolean */
/** @typedef {Object<string, string>} CssStyles */
/** @typedef {Object<string, string>} FontStyles */
/** @typedef {string|Array<string>} StyleItem */
/** @typedef {Object<string, StyleItem>} LogbookStyles */
/** @typedef {function(...string):void} ConsoleMethod window.console method */
/** @typedef {{ fn: ConsoleMethod, level?: validLogLevels, style?: StyleItem }} Logger */
/** @typedef {Object<string, Logger>} LogbookConfigList */
/** @typedef {Object<string, ConsoleMethod>} LogbookList */
/** @typedef {keyof typeof LogLevels} validLogLevels */
/** @typedef {typeof DefaultSettings} xSettings */
/**
* @typedef {Object} Settings
* @property {validLogLevels} [threshold] Log all messages of EQUAL or LESSER level.
* @property {string} [name] Name to use if the Logbook is attached to the window object
* @property {boolean} [overwriteConsole] Enable overwriting built-in console functions
* @property {string} [globalPrefix] Rename logger functions if exported as globals
* @property {boolean} [global] Export logger functions to global scope
*/
/**
* Default config.
*
* @type {Settings}
*/
const DefaultSettings = {
threshold: 'all',
name: 'Logbook',
overwriteConsole: false,
globalPrefix: '',
global: false,
}
/**
* Default log levels.
*
* @readonly
* @enum {number}
*/
const LogLevels = {
all: 1,
debug: 2,
log: 3,
trace: 4,
info: 5,
warn: 6,
error: 7,
disable: 8,
disabled: 8,
off: 8,
}
/** @type {CssStyles} */
const style = {
badge: 'padding: 2px 4px; border-radius: 3px;',
block: 'display: inline-block; width: 100%; padding: 2px 4px; margin: 2px 0;',
paddingXl: 'padding: 3px 15px;',
paddingLg: 'padding: 3px 10px;',
paddingSm: 'padding: 2px 5px;',
}
/** @type {FontStyles} */
const font = {
black: 'color: black;',
white: 'color: white;',
lg: 'font-size: 1.2em;',
xl: 'font-size: 1.4em;',
bold: 'font-weight: bold;',
}
/**
* Default Logbook CSS styling.
*
* @type {LogbookStyles}
*/
const defaultLogbookStyles = {
L1: [ style.badge, style.paddingXl, font.black, font.bold, `background: orange;` ],
L2: [ style.badge, style.paddingXl, font.black, `background: #90e5fe;` ],
L3: [ style.badge, style.paddingXl, font.black, ` background-color: lemonchiffon;` ],
L4: [ style.badge, style.paddingXl, font.black, `background-color: lavender;` ],
note: [ style.paddingSm, 'color: #FFDEAD;' ],
blue: [ style.block, style.paddingSm, font.black, 'background: deepskyblue;' ],
red: [ style.block, style.paddingSm, font.white, `background: darkred;` ],
purple: [ style.block, style.paddingSm, font.white, 'background: purple;' ],
yellow: [ style.block, style.paddingSm, font.black, `background: yellow;` ],
green: [ style.paddingSm, font.black, `display: inline-block; width: 90%; background: springgreen;` ],
bigYellow: [ style.block, style.paddingLg, font.lg, font.bold, font.black, `background: gold;` ],
warn: 'padding: 3px 10px;',
error: 'padding: 3px 10px;',
success: `color: #B1FB17;`,
info: 'color: #7DFDFE;',
debug: 'color: #FFDEAD;',
group: 'color: #FFDEAD;',
groupEnd: '',
}
/**
* @type {LogbookConfigList}
*/
const defaultLoggers = {
log: { fn: console.log },
warn: { fn: console.warn },
error: { fn: console.error },
info: { fn: console.info },
debug: { fn: console.debug },
group: { fn: console.group, level: 'log' },
groupEnd: { fn: console.groupEnd, level: 'log' },
L1: { fn: console.log, level: 'info' },
L2: { fn: console.log, level: 'info' },
L3: { fn: console.log, level: 'info' },
L4: { fn: console.log, level: 'info' },
note: { fn: console.log, level: 'info' },
blue: { fn: console.log, level: 'debug' },
red: { fn: console.log, level: 'debug' },
purple: { fn: console.log, level: 'debug' },
yellow: { fn: console.log, level: 'debug' },
green: { fn: console.log, level: 'debug' },
bigYellow: { fn: console.log, level: 'debug' },
}
/**
* Cached version of console.log.
*
* If the Logbook needs debugging.
*/
const __log = console.log.bind( window.console )
/**
* This makes it safe for Typescript.
*
* @param {...any} data
*/
// eslint-disable-next-line no-unused-vars
const __void = ( ...data ) => null
/**
* Initialize the Logbook library. Configure settings and loggers. Returns API. To export logger functions, use `logbook.export()`.
*
* Providing CSS to a logger function will apply that style to the first argument. Additional arguments will use default style.
*
* Note: it's not possible to use objects in arguments that are printed with formatting, it will result in `[object Object]`.
*
* 🛠🛠🛠 Arguments 🛠🛠🛠
*
* settings:
* ```
* {
* threshold?: string,
* name?: string,
* globalPrefix?: string,
* overwriteConsole?: boolean,
* global?: boolean,
* }
* ```
*
* Note: If overwriting console, only existing console methods are replaced -- custom loggers are not placed inside console.
*
* ```
* loggers:
* {
* [name]: {
* level: string, // valid logLevel
* consoleFn?: string, //name of console function, default = log
* style?: string, //CSS rules
* },
* [name]: null //disable logger
* }
* ```
*
* Logging levels (least to most restrictive):
* `[ all, log, trace, debug, info, warn, error, disable ]`
*
* @param {Settings} settings
* @param {LogbookConfigList} loggers
*/
function Logbook( settings, loggers = {} ) {
const currentConsole = console
const logbookSettings = DefaultSettings
const logbookStyles = defaultLogbookStyles
let thresholdIndex = 0
setup( settings )
// Merge provided loggers uncritically with defaults
const loggerConfigs = mergeConfigs( defaultLoggers, loggers )
registerLoggers()
// === Return public methods ===
const api = {
get settings() {
return logbookSettings
},
/**
* Change threshold and register/unregister loggers.
*
* Note: mutates exported loggers.
*
* @param {validLogLevels} threshold
*/
setLevel( threshold ) {
logbookSettings.threshold = getLevelInt( threshold ) ? threshold : 'all'
registerLoggers()
},
/**
* Get information about current configuration and available loggers.
*/
// eslint-disable-next-line no-shadow
help( { all = false, loggers = false, loggersVerbose = false, defaults = false, levels = false, settings = false } = {} ) {
const output = {
...( loggers || all ) && { loggers: currentConsole },
...( loggersVerbose || all ) && { loggersVerbose: loggerConfigs },
...( defaults || all ) && { defaults: defaultLoggers },
...( levels || all ) && { levels: LogLevels },
...( settings || all ) && { settings: logbookSettings },
}
let i
for ( i in output ) {}
if ( ! i ) {
__log( '*** Example usage: ***\n\nhelp({ all = false, loggers = true, loggersVerbose = false, defaults = false, levels = false, settings = false })' )
return
}
__log( output )
},
/**
* Create new logger or modify an existing logger.
*
* @param {string} name
* @param {Logger} config
*/
register( name, config ) {
return getLoggerFn( name, config )
},
/**
* Export all logger functions wrapped in an object.
*
* Note: destructured functions will NOT be updated if the configuration or threshold is changed after export.
*/
export() {
return currentConsole
},
/**
* Print test message with all registered loggers.
*/
test() {
Object.keys( loggerConfigs ).forEach( ( logger ) => {
currentConsole[ logger ]( `Test: ${ logger }` )
} )
},
}
if ( logbookSettings.global ) {
// eslint-disable-next-line dot-notation
window[ 'logger' ] = api
// eslint-disable-next-line dot-notation
window[ '__log' ] = __log
}
// === Private functions ===
/**
* @internal
* @param {validLogLevels} levelString
*/
function getLevelInt( levelString ) {
return LogLevels[ levelString ]
}
/**
* @internal
* @param {Settings} _settings
*/
function setup( _settings = DefaultSettings ) {
const { global, globalPrefix, threshold, overwriteConsole } = _settings
logbookSettings.threshold = isValid( threshold, logbookSettings.threshold, 'all' )
thresholdIndex = getLevelInt( logbookSettings.threshold )
logbookSettings.global = isValid( global, logbookSettings.global )
logbookSettings.overwriteConsole = isValid( overwriteConsole, logbookSettings.overwriteConsole )
logbookSettings.globalPrefix = isValid( globalPrefix, logbookSettings.globalPrefix, '' )
}
/**
* Process logger configurations and register loggers based on current threshold.
*
* @internal
*/
function registerLoggers() {
const names = Object.keys( loggerConfigs )
names.forEach( ( name ) => {
const config = loggerConfigs[ name ]
config.level = config.level || name
editLogger( name, config )
} )
}
/**
* Generate console method based on config.
*
* @internal
* @param {string} name
* @param {Logger} config
* @return {ConsoleMethod} Returns a wrapped console method.
*/
function getLoggerFn( name, config ) {
const { fn: consoleFn, style: loggerStyle } = config
// ~ The magic happens here ~
// Prepending the console message array with two items [`%c%s`, CSS] will apply that CSS to the next item added to the array.
// %c%s is a template string. %c is replaced by the next item in the list, which is the CSS. %s is replaced by the message string, the item that is following the CSS.
// The CSS will only be applied to one array item
// Subsequent items added to the array, .e.g. console.log(..., item2, item3, ...) will revert to default styling
// Specification: @see https://developer.mozilla.org/en-US/docs/Web/API/Console#outputting_text_to_the_console
// Note: only primitive values can be styled, objects will be stringified as [object Object]
// #todo: use %O to output objects
// ! Note: it is critical for the first params array item to bind console to 'this'
const params = loggerStyle
? [ console, `%c%s`, loggerStyle ]
: [ console ]
let logger
try {
logger = Function.prototype.bind.apply( consoleFn, params )
}
catch ( err ) {
console.error( `Logbook: Failed to register logger, invalid console function provided (name: ${ name }).` )
logger = undefined
}
return logger
}
/**
* Add new logger or reconfigure an existing one. New settings are merged with old.
*
* @internal
* @param {string} name
* @param {Logger} config
*/
function editLogger( name, config ) {
const { level, style: loggerStyle } = config
let levelIndex = getLevelInt( level )
if ( ! levelIndex ) {
config.level = 'all'
levelIndex = 1
}
config.style = loggerStyle
if ( ! loggerStyle ) {
config.style = logbookStyles[ name ]
if ( Array.isArray( config.style ) ) {
config.style = config.style.join( '' )
}
}
if ( loggerConfigs[ name ] ) {
loggerConfigs[ name ] = { ...loggerConfigs[ name ], ...config }
}
else {
loggerConfigs[ name ] = config
}
const logger = getLoggerFn( name, config )
if ( ! logger ) {
return
}
const fn = levelIndex >= thresholdIndex ? logger : __void
if ( logbookSettings.overwriteConsole && window.console[ name ] ) {
window.console[ name ] = fn
}
currentConsole[ name ] = fn
// Add logger to window?
if ( logbookSettings.global ) {
const globalName = logbookSettings.globalPrefix ? logbookSettings.globalPrefix + name : name
window[ globalName ] = fn
}
}
return api
}
/**
* Simple merge function for two objects with two levels, with minimal guards.
*
* Provide target to merge objects by mutation.
*
* @param {Object<string, any>} obj1 - Object to merge into.
* @param {Object<string, any>} obj2 - Obj2 props will overwrite obj1 props, recursively.
* @param {Object<string, any>} target - Optional. If provided, objects will be merged with target by mutation.
* @return {Object<string, any>} Merged object
*/
function mergeConfigs( obj1, obj2, target = {} ) {
const obj1Keys = Object.keys( obj1 )
const obj2Keys = Object.keys( obj2 )
obj1Keys.concat( obj2Keys ).forEach( ( key ) => {
target[ key ] = Object.assign( obj1[ key ] || {}, obj2[ key ] || {} )
} )
return target
}
function isValid( value, fallback, compare = undefined ) {
return value !== compare && value !== undefined ? value : fallback
}
export default Logbook