diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index c256202..0000000 --- a/.eslintignore +++ /dev/null @@ -1,4 +0,0 @@ -lib/ -tmp/ -examples/app/bundle.js - diff --git a/.eslintrc.yml b/.eslintrc.yml deleted file mode 100644 index 6461faf..0000000 --- a/.eslintrc.yml +++ /dev/null @@ -1,12 +0,0 @@ -env: - browser: true - es2021: true - node: true - mocha: true -extends: standard -overrides: [] -parserOptions: - ecmaVersion: latest - sourceType: module -rules: - n/no-deprecated-api: warn diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6b9a366..82098c2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [ 20 ] + node: [ 20, 22 ] name: Node ${{ matrix.node }} steps: - uses: actions/checkout@v4 diff --git a/CHANGELOG.md b/CHANGELOG.md index 43f8806..2c75571 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +# 4.0.0 (2025-02-09) + +- fix: linting with eslint prettier (#e309f0e) +- BREAKING CHANGE: min supported node@18 (#0375148) +- chore: bump dependencies (#8af1300) +- chore(ci): add node@22 (#2c097a4) + # 3.2.1 (2024-10-04) - chore: bump dependencies (#5e03ed9) @@ -5,8 +12,8 @@ # 3.2.0 (2024-07-21) -- docs: update ci badge (#e99f6b2) - chore: deprecate node 18 (#f3931fe) +- docs: update ci badge (#e99f6b2) - chore: bump dependencies (#5b4de1f) # 3.1.4 (2024-03-13) @@ -149,3 +156,4 @@ - first version (#41890c0) - Initial commit (#d298779) + diff --git a/benchmarks/basic.bench.js b/benchmarks/basic.bench.js index 87c18a3..d383b6c 100644 --- a/benchmarks/basic.bench.js +++ b/benchmarks/basic.bench.js @@ -3,45 +3,42 @@ const bench = require('fastbench') const max = JSON.parse(process.env.MAX || 10000) const stream = max === 1 ? process.stderr : undefined -const { - bunyan, - debug, - pino, - pinoAsync, - debugLevel, - debugLevelAsync -} = require('./instances.js')(stream) +const { bunyan, debug, pino, pinoAsync, debugLevel, debugLevelAsync } = + require('./instances.js')(stream) -const run = bench([ - function benchDebug (done) { - debug('hello world') - process.nextTick(done) - }, - function benchBunyan (done) { - bunyan.debug('hello world') - process.nextTick(done) - }, - function benchPino (done) { - pino.debug('hello world') - process.nextTick(done) - }, - function benchDebugLevel (done) { - debugLevel.debug('hello world') - process.nextTick(done) - }, - function benchPinoAsync (done) { - pinoAsync.debug('hello world') - process.nextTick(done) - }, - function benchDebugLevelAsync (done) { - debugLevelAsync.debug('hello world') - process.nextTick(done) - } -], max) +const run = bench( + [ + function benchDebug(done) { + debug('hello world') + process.nextTick(done) + }, + function benchBunyan(done) { + bunyan.debug('hello world') + process.nextTick(done) + }, + function benchPino(done) { + pino.debug('hello world') + process.nextTick(done) + }, + function benchDebugLevel(done) { + debugLevel.debug('hello world') + process.nextTick(done) + }, + function benchPinoAsync(done) { + pinoAsync.debug('hello world') + process.nextTick(done) + }, + function benchDebugLevelAsync(done) { + debugLevelAsync.debug('hello world') + process.nextTick(done) + } + ], + max +) const final = () => { pinoAsync.flush() debugLevelAsync.flush() } -run((final)) +run(final) diff --git a/benchmarks/deep-j.bench.js b/benchmarks/deep-j.bench.js index 50a3e4c..48b12e0 100644 --- a/benchmarks/deep-j.bench.js +++ b/benchmarks/deep-j.bench.js @@ -3,49 +3,46 @@ const bench = require('fastbench') const max = JSON.parse(process.env.MAX || 10000) const stream = max === 1 ? process.stderr : undefined -const { - bunyan, - debug, - pino, - pinoAsync, - debugLevel, - debugLevelAsync -} = require('./instances.js')(stream) +const { bunyan, debug, pino, pinoAsync, debugLevel, debugLevelAsync } = + require('./instances.js')(stream) const deep = require('../package.json') deep.deep = Object.assign({}, JSON.parse(JSON.stringify(deep))) deep.deep.deep = Object.assign({}, JSON.parse(JSON.stringify(deep))) -const run = bench([ - function benchDebug (done) { - debug('deep %j', deep) - process.nextTick(done) - }, - function benchBunyan (done) { - bunyan.debug('deep %j', deep) - process.nextTick(done) - }, - function benchPino (done) { - pino.debug('deep %j', deep) - process.nextTick(done) - }, - function benchDebugLevel (done) { - debugLevel.debug('deep %j', deep) - process.nextTick(done) - }, - function benchPinoAsync (done) { - pinoAsync.debug('deep %j', deep) - process.nextTick(done) - }, - function benchDebugLevelAsync (done) { - debugLevelAsync.debug('deep %j', deep) - process.nextTick(done) - } -], max) +const run = bench( + [ + function benchDebug(done) { + debug('deep %j', deep) + process.nextTick(done) + }, + function benchBunyan(done) { + bunyan.debug('deep %j', deep) + process.nextTick(done) + }, + function benchPino(done) { + pino.debug('deep %j', deep) + process.nextTick(done) + }, + function benchDebugLevel(done) { + debugLevel.debug('deep %j', deep) + process.nextTick(done) + }, + function benchPinoAsync(done) { + pinoAsync.debug('deep %j', deep) + process.nextTick(done) + }, + function benchDebugLevelAsync(done) { + debugLevelAsync.debug('deep %j', deep) + process.nextTick(done) + } + ], + max +) const final = () => { pinoAsync.flush() debugLevelAsync.flush() } -run((final)) +run(final) diff --git a/benchmarks/deep.bench.js b/benchmarks/deep.bench.js index 8d04d21..9d0a2f6 100644 --- a/benchmarks/deep.bench.js +++ b/benchmarks/deep.bench.js @@ -3,49 +3,46 @@ const bench = require('fastbench') const max = JSON.parse(process.env.MAX || 10000) const stream = max === 1 ? process.stderr : undefined -const { - bunyan, - debug, - pino, - pinoAsync, - debugLevel, - debugLevelAsync -} = require('./instances.js')(stream) +const { bunyan, debug, pino, pinoAsync, debugLevel, debugLevelAsync } = + require('./instances.js')(stream) const deep = require('../package.json') deep.deep = Object.assign({}, JSON.parse(JSON.stringify(deep))) deep.deep.deep = Object.assign({}, JSON.parse(JSON.stringify(deep))) -const run = bench([ - function benchDebug (done) { - debug(deep) - process.nextTick(done) - }, - function benchBunyan (done) { - bunyan.debug(deep) - process.nextTick(done) - }, - function benchPino (done) { - pino.debug(deep) - process.nextTick(done) - }, - function benchDebugLevel (done) { - debugLevel.debug(deep) - process.nextTick(done) - }, - function benchPinoAsync (done) { - pinoAsync.debug(deep) - process.nextTick(done) - }, - function benchDebugLevelAsync (done) { - debugLevelAsync.debug(deep) - process.nextTick(done) - } -], max) +const run = bench( + [ + function benchDebug(done) { + debug(deep) + process.nextTick(done) + }, + function benchBunyan(done) { + bunyan.debug(deep) + process.nextTick(done) + }, + function benchPino(done) { + pino.debug(deep) + process.nextTick(done) + }, + function benchDebugLevel(done) { + debugLevel.debug(deep) + process.nextTick(done) + }, + function benchPinoAsync(done) { + pinoAsync.debug(deep) + process.nextTick(done) + }, + function benchDebugLevelAsync(done) { + debugLevelAsync.debug(deep) + process.nextTick(done) + } + ], + max +) const final = () => { pinoAsync.flush() debugLevelAsync.flush() } -run((final)) +run(final) diff --git a/benchmarks/format-s.bench.js b/benchmarks/format-s.bench.js index 95f42eb..323a03b 100644 --- a/benchmarks/format-s.bench.js +++ b/benchmarks/format-s.bench.js @@ -3,45 +3,42 @@ const bench = require('fastbench') const max = JSON.parse(process.env.MAX || 10000) const stream = max === 1 ? process.stderr : undefined -const { - bunyan, - debug, - pino, - pinoAsync, - debugLevel, - debugLevelAsync -} = require('./instances.js')(stream) +const { bunyan, debug, pino, pinoAsync, debugLevel, debugLevelAsync } = + require('./instances.js')(stream) -const run = bench([ - function benchDebug (done) { - debug('hello %s', 'world') - process.nextTick(done) - }, - function benchBunyan (done) { - bunyan.debug('hello %s', 'world') - process.nextTick(done) - }, - function benchPino (done) { - pino.debug('hello %s', 'world') - process.nextTick(done) - }, - function benchDebugLevel (done) { - debugLevel.debug('hello %s', 'world') - process.nextTick(done) - }, - function benchPinoAsync (done) { - pinoAsync.debug('hello %s', 'world') - process.nextTick(done) - }, - function benchDebugLevelAsync (done) { - debugLevelAsync.debug('hello %s', 'world') - process.nextTick(done) - } -], max) +const run = bench( + [ + function benchDebug(done) { + debug('hello %s', 'world') + process.nextTick(done) + }, + function benchBunyan(done) { + bunyan.debug('hello %s', 'world') + process.nextTick(done) + }, + function benchPino(done) { + pino.debug('hello %s', 'world') + process.nextTick(done) + }, + function benchDebugLevel(done) { + debugLevel.debug('hello %s', 'world') + process.nextTick(done) + }, + function benchPinoAsync(done) { + pinoAsync.debug('hello %s', 'world') + process.nextTick(done) + }, + function benchDebugLevelAsync(done) { + debugLevelAsync.debug('hello %s', 'world') + process.nextTick(done) + } + ], + max +) const final = () => { pinoAsync.flush() debugLevelAsync.flush() } -run((final)) +run(final) diff --git a/benchmarks/format-sjd.bench.js b/benchmarks/format-sjd.bench.js index bff3a5a..101e355 100644 --- a/benchmarks/format-sjd.bench.js +++ b/benchmarks/format-sjd.bench.js @@ -3,45 +3,52 @@ const bench = require('fastbench') const max = JSON.parse(process.env.MAX || 10000) const stream = max === 1 ? process.stderr : undefined -const { - bunyan, - debug, - pino, - pinoAsync, - debugLevel, - debugLevelAsync -} = require('./instances.js')(stream) +const { bunyan, debug, pino, pinoAsync, debugLevel, debugLevelAsync } = + require('./instances.js')(stream) -const run = bench([ - function benchDebug (done) { - debug('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' }) - process.nextTick(done) - }, - function benchBunyan (done) { - bunyan.debug('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' }) - process.nextTick(done) - }, - function benchPino (done) { - pino.debug('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' }) - process.nextTick(done) - }, - function benchDebugLevel (done) { - debugLevel.debug('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' }) - process.nextTick(done) - }, - function benchPinoAsync (done) { - pinoAsync.debug('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' }) - process.nextTick(done) - }, - function benchDebugLevelAsync (done) { - debugLevelAsync.debug('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' }) - process.nextTick(done) - } -], max) +const run = bench( + [ + function benchDebug(done) { + debug('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' }) + process.nextTick(done) + }, + function benchBunyan(done) { + bunyan.debug('hello %s %j %d', 'world', { obj: true }, 4, { + another: 'obj' + }) + process.nextTick(done) + }, + function benchPino(done) { + pino.debug('hello %s %j %d', 'world', { obj: true }, 4, { + another: 'obj' + }) + process.nextTick(done) + }, + function benchDebugLevel(done) { + debugLevel.debug('hello %s %j %d', 'world', { obj: true }, 4, { + another: 'obj' + }) + process.nextTick(done) + }, + function benchPinoAsync(done) { + pinoAsync.debug('hello %s %j %d', 'world', { obj: true }, 4, { + another: 'obj' + }) + process.nextTick(done) + }, + function benchDebugLevelAsync(done) { + debugLevelAsync.debug('hello %s %j %d', 'world', { obj: true }, 4, { + another: 'obj' + }) + process.nextTick(done) + } + ], + max +) const final = () => { pinoAsync.flush() debugLevelAsync.flush() } -run((final)) +run(final) diff --git a/benchmarks/instances.js b/benchmarks/instances.js index 6840633..06d2375 100644 --- a/benchmarks/instances.js +++ b/benchmarks/instances.js @@ -6,7 +6,7 @@ const bunyanF = require('bunyan') const pinoF = require('pino') const { Log: DebugLevel } = require('..') -function setup (stream) { +function setup(stream) { if (!stream) { stream = fs.createWriteStream('/dev/null') } @@ -16,24 +16,43 @@ function setup (stream) { const bunyan = bunyanF.createLogger({ name, - streams: [{ - level, - stream - }] + streams: [ + { + level, + stream + } + ] }) const debug = debugF(name) debug.inspectOpts.depth = Infinity if (path) { - debug.log = function (s) { stream.write(s) } + debug.log = function (s) { + stream.write(s) + } } const pino = pinoF({ name, level }, stream) - const pinoAsync = pinoF({ name, level }, pinoF.destination({ dest: path, fd, sync: true, minLength: 4096 })) + const pinoAsync = pinoF( + { name, level }, + pinoF.destination({ dest: path, fd, sync: true, minLength: 4096 }) + ) DebugLevel.options({ json: true, colors: false, namespaces: '*' }) - const debugLevel = new DebugLevel(name, { level, stream, sonic: false, serverinfo: true, timestamp: 'epoch' }) - const debugLevelAsync = new DebugLevel(name, { level, stream, sonic: true, serverinfo: true, timestamp: 'epoch' }) + const debugLevel = new DebugLevel(name, { + level, + stream, + sonic: false, + serverinfo: true, + timestamp: 'epoch' + }) + const debugLevelAsync = new DebugLevel(name, { + level, + stream, + sonic: true, + serverinfo: true, + timestamp: 'epoch' + }) return { bunyan, diff --git a/benchmarks/long-string.bench.js b/benchmarks/long-string.bench.js index 68fb2c5..6f08bf1 100644 --- a/benchmarks/long-string.bench.js +++ b/benchmarks/long-string.bench.js @@ -3,49 +3,50 @@ const bench = require('fastbench') const max = JSON.parse(process.env.MAX || 10000) const stream = max === 1 ? process.stderr : undefined -const { - bunyan, - debug, - pino, - pinoAsync, - debugLevel, - debugLevelAsync -} = require('./instances.js')(stream) +const { bunyan, debug, pino, pinoAsync, debugLevel, debugLevelAsync } = + require('./instances.js')(stream) -const a = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_*#$%&!"\'' -const random = () => a[Math.random() * a.length | 0] -const longStr = new Array(2000).fill('').map(() => random()).join('') +const a = + 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_*#$%&!"\'' +const random = () => a[(Math.random() * a.length) | 0] +const longStr = new Array(2000) + .fill('') + .map(() => random()) + .join('') -const run = bench([ - function benchDebug (done) { - debug(longStr) - process.nextTick(done) - }, - function benchBunyan (done) { - bunyan.debug(longStr) - process.nextTick(done) - }, - function benchPino (done) { - pino.debug(longStr) - process.nextTick(done) - }, - function benchDebugLevel (done) { - debugLevel.debug(longStr) - process.nextTick(done) - }, - function benchPinoAsync (done) { - pinoAsync.debug(longStr) - process.nextTick(done) - }, - function benchDebugLevelAsync (done) { - debugLevelAsync.debug(longStr) - process.nextTick(done) - } -], max) +const run = bench( + [ + function benchDebug(done) { + debug(longStr) + process.nextTick(done) + }, + function benchBunyan(done) { + bunyan.debug(longStr) + process.nextTick(done) + }, + function benchPino(done) { + pino.debug(longStr) + process.nextTick(done) + }, + function benchDebugLevel(done) { + debugLevel.debug(longStr) + process.nextTick(done) + }, + function benchPinoAsync(done) { + pinoAsync.debug(longStr) + process.nextTick(done) + }, + function benchDebugLevelAsync(done) { + debugLevelAsync.debug(longStr) + process.nextTick(done) + } + ], + max +) const final = () => { pinoAsync.flush() debugLevelAsync.flush() } -run((final)) +run(final) diff --git a/benchmarks/obj.bench.js b/benchmarks/obj.bench.js index 93d83c9..ad75b1d 100644 --- a/benchmarks/obj.bench.js +++ b/benchmarks/obj.bench.js @@ -3,47 +3,44 @@ const bench = require('fastbench') const max = JSON.parse(process.env.MAX || 10000) const stream = max === 1 ? process.stderr : undefined -const { - bunyan, - debug, - pino, - pinoAsync, - debugLevel, - debugLevelAsync -} = require('./instances.js')(stream) +const { bunyan, debug, pino, pinoAsync, debugLevel, debugLevelAsync } = + require('./instances.js')(stream) const obj = { msg: 'the message', string: 'string', number: 42, bool: true } -const run = bench([ - function benchDebug (done) { - debug(obj) - process.nextTick(done) - }, - function benchBunyan (done) { - bunyan.debug(obj) - process.nextTick(done) - }, - function benchPino (done) { - pino.debug(obj) - process.nextTick(done) - }, - function benchDebugLevel (done) { - debugLevel.debug(obj) - process.nextTick(done) - }, - function benchPinoAsync (done) { - pinoAsync.debug(obj) - process.nextTick(done) - }, - function benchDebugLevelAsync (done) { - debugLevelAsync.debug(obj) - process.nextTick(done) - } -], max) +const run = bench( + [ + function benchDebug(done) { + debug(obj) + process.nextTick(done) + }, + function benchBunyan(done) { + bunyan.debug(obj) + process.nextTick(done) + }, + function benchPino(done) { + pino.debug(obj) + process.nextTick(done) + }, + function benchDebugLevel(done) { + debugLevel.debug(obj) + process.nextTick(done) + }, + function benchPinoAsync(done) { + pinoAsync.debug(obj) + process.nextTick(done) + }, + function benchDebugLevelAsync(done) { + debugLevelAsync.debug(obj) + process.nextTick(done) + } + ], + max +) const final = () => { pinoAsync.flush() debugLevelAsync.flush() } -run((final)) +run(final) diff --git a/benchmarks/run.js b/benchmarks/run.js index b77e9f6..b7c65a2 100644 --- a/benchmarks/run.js +++ b/benchmarks/run.js @@ -2,20 +2,41 @@ const { spawnSync } = require('child_process') const { join } = require('path') const files = [ - { file: 'basic.bench.js', name: 'Basic String', fmt: "log.debug('hello world')" }, - { file: 'long-string.bench.js', name: 'Long String 2000 chars', fmt: "log.debug('...2000chars...')" }, - { file: 'format-s.bench.js', name: 'Hello World with %s format', fmt: "log.debug('hello %s', 'world')" }, - { file: 'format-sjd.bench.js', name: 'Multi Argument format', fmt: "log.debug('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' })" }, - { file: 'obj.bench.js', name: 'Object', fmt: "log.debug({ msg: 'the message',string: 'string',number: 42,bool: true })" }, + { + file: 'basic.bench.js', + name: 'Basic String', + fmt: "log.debug('hello world')" + }, + { + file: 'long-string.bench.js', + name: 'Long String 2000 chars', + fmt: "log.debug('...2000chars...')" + }, + { + file: 'format-s.bench.js', + name: 'Hello World with %s format', + fmt: "log.debug('hello %s', 'world')" + }, + { + file: 'format-sjd.bench.js', + name: 'Multi Argument format', + fmt: "log.debug('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' })" + }, + { + file: 'obj.bench.js', + name: 'Object', + fmt: "log.debug({ msg: 'the message',string: 'string',number: 42,bool: true })" + }, { file: 'deep.bench.js', name: 'Deep Object', fmt: 'log.debug(deep)' }, - { file: 'deep-j.bench.js', name: 'Deep Object with %j format', fmt: "log.debug('deep %j', deep)" } + { + file: 'deep-j.bench.js', + name: 'Deep Object with %j format', + fmt: "log.debug('deep %j', deep)" + } ] files.forEach(({ file, name, fmt }) => { - let { stdout, stderr } = spawnSync( - process.argv[0], - [join(__dirname, file)] - ) + let { stdout, stderr } = spawnSync(process.argv[0], [join(__dirname, file)]) if (stderr.length) { stdout = stderr @@ -28,6 +49,5 @@ files.forEach(({ file, name, fmt }) => { \`\`\` ${stdout} -\`\`\`` - ) +\`\`\``) }) diff --git a/benchmarks/single.js b/benchmarks/single.js index 9e402b7..5aacaf1 100644 --- a/benchmarks/single.js +++ b/benchmarks/single.js @@ -18,28 +18,31 @@ const { // obj.deep = clean(obj) const obj = { string: 'lala', foo: 42, is: true } -const f = () => (['hello %j', obj]) +const f = () => ['hello %j', obj] // const f = () => ([obj]) -const run = bench([ - function benchPino (done) { - // debugger - pino.debug(...f()) - process.nextTick(done) - }, - function benchDebugLevel (done) { - // debugger - debugLevel.debug(...f()) - process.nextTick(done) - } - // function benchPinoAsync (done) { - // pinoAsync.debug(deep) - // process.nextTick(done) - // }, - // function benchDebugLevelAsync (done) { - // debugLevelAsync.debug(deep) - // process.nextTick(done) - // } -], max) +const run = bench( + [ + function benchPino(done) { + // debugger + pino.debug(...f()) + process.nextTick(done) + }, + function benchDebugLevel(done) { + // debugger + debugLevel.debug(...f()) + process.nextTick(done) + } + // function benchPinoAsync (done) { + // pinoAsync.debug(deep) + // process.nextTick(done) + // }, + // function benchDebugLevelAsync (done) { + // debugLevelAsync.debug(deep) + // process.nextTick(done) + // } + ], + max +) run(run) diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 0000000..53b617d --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,24 @@ +import globals from 'globals' +import pluginPrettier from 'eslint-plugin-prettier/recommended' + +const config = [ + { languageOptions: { globals: { ...globals.node, ...globals.mocha } } }, + pluginPrettier, + { + rules: { + 'no-unused-vars': [ + 'error', + { + varsIgnorePattern: '^_$', + argsIgnorePattern: '^_', + caughtErrors: 'none' + } + ] + } + }, + { + ignores: ['coverage/', 'docs/', 'tmp/', 'examples/app/bundle.js'] + } +] + +export default config diff --git a/examples/app/index.js b/examples/app/index.js index 5740313..b2aa277 100644 --- a/examples/app/index.js +++ b/examples/app/index.js @@ -7,9 +7,10 @@ window.localStorage.setItem('DEBUG_LEVEL', 'TRACE') const log = new Log('myApp') const ORD = ['th', 'st', 'nd', 'rd'] -const ordinals = (num) => num + (num > 10 && num < 14 ? 'th' : ORD[num % 10] || ORD[0]) +const ordinals = (num) => + num + (num > 10 && num < 14 ? 'th' : ORD[num % 10] || ORD[0]) const LEVEL = ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'] -const levels = () => LEVEL[Math.random() * LEVEL.length | 0] +const levels = () => LEVEL[(Math.random() * LEVEL.length) | 0] let count = 1 setInterval(() => { diff --git a/examples/app/server.cjs b/examples/app/server.cjs index 6de03a2..67b65c6 100644 --- a/examples/app/server.cjs +++ b/examples/app/server.cjs @@ -9,7 +9,7 @@ const log = new Log('server') const logMw = browserLogs() const port = 3000 -function serveStatic (req, res) { +function serveStatic(req, res) { const url = join(__dirname, '.', req.url) fs.stat(url, (err) => { if (err) { @@ -20,18 +20,20 @@ function serveStatic (req, res) { }) } -http.createServer((req, res) => { - log.info(req.url) +http + .createServer((req, res) => { + log.info(req.url) - if (/^\/debug-level/.test(req.url)) { - req.ip = req.ip || req.socket.remoteAddress - logMw(req, res) - } else { - if (req.url === '/') { - req.url = '/index.html' + if (/^\/debug-level/.test(req.url)) { + req.ip = req.ip || req.socket.remoteAddress + logMw(req, res) + } else { + if (req.url === '/') { + req.url = '/index.html' + } + serveStatic(req, res) } - serveStatic(req, res) - } -}).listen(port, () => { - console.log(`\n browse to http://localhost:${port}\n\n`) -}) + }) + .listen(port, () => { + console.log(`\n browse to http://localhost:${port}\n\n`) + }) diff --git a/examples/app/webpack.config.cjs b/examples/app/webpack.config.cjs index 6599488..1c3047b 100644 --- a/examples/app/webpack.config.cjs +++ b/examples/app/webpack.config.cjs @@ -19,6 +19,5 @@ module.exports = { } ] }, - plugins: [ - ] + plugins: [] } diff --git a/examples/client.js b/examples/client.js index 2265026..a87d61f 100644 --- a/examples/client.js +++ b/examples/client.js @@ -4,9 +4,10 @@ import { logger } from '../src/index.js' const logA = logger('client:A') const logB = logger('client:B') -function client (log, path) { - function request () { - http.get({ host: 'localhost', port: '3000', path }) +function client(log, path) { + function request() { + http + .get({ host: 'localhost', port: '3000', path }) .on('response', (res) => { const status = res.statusCode res.on('data', (chunk) => { diff --git a/examples/jsonOutput.cjs b/examples/jsonOutput.cjs index 6ece16d..1cc6de9 100644 --- a/examples/jsonOutput.cjs +++ b/examples/jsonOutput.cjs @@ -5,7 +5,13 @@ const log = new Log('package') // ---- // use formatters (NOT RECOMMENDED for objects, errors) -log.debug('a %s, a number %d, an %o and %j', 'string', 1.2, { object: 1 }, { NOT: 'RECOMMENDED' }) +log.debug( + 'a %s, a number %d, an %o and %j', + 'string', + 1.2, + { object: 1 }, + { NOT: 'RECOMMENDED' } +) /* > { "level": "DEBUG", "name": "package", @@ -77,13 +83,14 @@ log.info('formatter %s', 'message1', 'message2', 'message3') // ---- // using toJSON custom serializers -function reqToJSON () { +function reqToJSON() { const { ip, method, url, headers } = this const userAgent = headers ? headers['user-agent'] : undefined return { ip, method, url, userAgent } } -const req = { // a client request +const req = { + // a client request method: 'GET', url: '/path', ip: '10.10.10.10', @@ -92,12 +99,13 @@ const req = { // a client request } req.toJSON = reqToJSON -function resToJSON () { +function resToJSON() { const { statusCode } = this return { statusCode } } -const res = { // a server response +const res = { + // a server response statusCode: 403, socket: {} // .... } diff --git a/examples/options.js b/examples/options.js index 0f7957f..ce62f7c 100644 --- a/examples/options.js +++ b/examples/options.js @@ -16,7 +16,13 @@ Log.options({ const log = new Log('*') log.debug({ object: 1 }) // ... -log.debug('a %s, a number %d, an %o and %j', 'string', 1.2, { object: 1 }, { json: true }) +log.debug( + 'a %s, a number %d, an %o and %j', + 'string', + 1.2, + { object: 1 }, + { json: true } +) log.debug({ object: 1 }, { json: true }) const err = new Error('bam') err.status = 500 diff --git a/examples/server.js b/examples/server.js index d0d1c8b..95ff3e3 100644 --- a/examples/server.js +++ b/examples/server.js @@ -7,23 +7,25 @@ const logHttpMw = httpLogs() const log = new Log('server') const codes = [200, 200, 200, 404, 500] -const randomStatus = () => codes[Math.random() * codes.length | 0] +const randomStatus = () => codes[(Math.random() * codes.length) | 0] // fake app log.info('booting %o', name) -http.createServer(function (req, res) { - log.debug('%s %s', req.method, req.url) - - logHttpMw(req, res, () => {}) - - const str = req.url.replace(/[/]/g, '') - res.statusCode = randomStatus() - // res.setHeader('Set-Cookie', ['foo=bar', 'session=foobar']) - res.setHeader('Set-Cookie', 'session=foobar') - res.end(`hello ${str}`) -}).listen(3000, function () { - log.info('listening') -}) +http + .createServer(function (req, res) { + log.debug('%s %s', req.method, req.url) + + logHttpMw(req, res, () => {}) + + const str = req.url.replace(/[/]/g, '') + res.statusCode = randomStatus() + // res.setHeader('Set-Cookie', ['foo=bar', 'session=foobar']) + res.setHeader('Set-Cookie', 'session=foobar') + res.end(`hello ${str}`) + }) + .listen(3000, function () { + log.info('listening') + }) import('./client.js') diff --git a/examples/toJSON.cjs b/examples/toJSON.cjs index 60c5e91..c4cb15c 100644 --- a/examples/toJSON.cjs +++ b/examples/toJSON.cjs @@ -1,7 +1,7 @@ const { Log } = require('..') const log = new Log('req', { json: false }) -function reqToJSON () { +function reqToJSON() { const { ip, method, url } = this return { ip, method, url } } diff --git a/karma.conf.cjs b/karma.conf.cjs index 902a31f..91a2bf3 100644 --- a/karma.conf.cjs +++ b/karma.conf.cjs @@ -2,7 +2,7 @@ const karmaTestMiddleware = require('./test/helpers/karma-test-middleware.cjs') const path = require('path') // Reference: http://karma-runner.github.io/0.13/config/configuration-file.html -module.exports = function karmaConfig (config) { +module.exports = function karmaConfig(config) { config.set({ browsers: [ 'Firefox', @@ -45,10 +45,7 @@ module.exports = function karmaConfig (config) { // Configure code coverage reporter coverageReporter: { - reporters: [ - { type: 'html', dir: 'coverage/' }, - { type: 'text' } - ] + reporters: [{ type: 'html', dir: 'coverage/' }, { type: 'text' }] }, client: { diff --git a/package.json b/package.json index f19f9f8..a772b3a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "debug-level", - "version": "3.2.1", + "version": "4.0.0-0", "description": "debug with levels", "keywords": [ "debug", @@ -16,6 +16,7 @@ }, "license": "MIT", "author": "commenthol ", + "sideEffects": false, "type": "module", "exports": { ".": { @@ -59,7 +60,7 @@ "coveralls": "npm run build && c8 npm test && c8 report --reporter=text-lcov | coveralls", "example": "npm run build:example && npm run start:example", "changelog": "conv-changelog -i CHANGELOG.md -o", - "lint": "eslint --ext .js .", + "lint": "eslint .", "readme": "markedpp --github -i README.md -o README.md", "start:example": "DEBUG=* node examples/app/server.cjs", "test": "mocha", @@ -78,21 +79,21 @@ "flatstr": "^1.0.12", "map-lru": "^2.1.0", "ms": "^2.1.3", - "sonic-boom": "^4.1.0" + "sonic-boom": "^4.2.0" }, "devDependencies": { - "@babel/cli": "^7.25.7", - "@babel/core": "^7.25.7", - "@babel/preset-env": "^7.25.7", + "@types/node": "^22.13.1", + "@babel/cli": "^7.26.4", + "@babel/core": "^7.26.8", + "@babel/preset-env": "^7.26.8", "assert": "^2.1.0", "babel-loader": "^9.2.1", - "c8": "^10.1.2", + "c8": "^10.1.3", "conv-changelog": "^1.0.0", - "eslint": "^8.57.1", - "eslint-config-standard": "^17.1.0", - "eslint-plugin-import": "^2.31.0", - "eslint-plugin-n": "^16.6.2", - "eslint-plugin-promise": "^6.6.0", + "globals": "^15.14.0", + "eslint": "^9.20.0", + "eslint-config-prettier": "^10.0.1", + "eslint-plugin-prettier": "^5.2.3", "karma": "^6.4.4", "karma-chrome-launcher": "^3.2.0", "karma-coverage": "^2.2.1", @@ -101,20 +102,20 @@ "karma-sourcemap-loader": "^0.4.0", "karma-spec-reporter": "^0.0.36", "karma-webpack": "^5.0.1", - "mocha": "^10.7.3", - "npm-run-all2": "^6.2.3", + "mocha": "^11.1.0", + "npm-run-all2": "^7.0.2", "rimraf": "^6.0.1", - "rollup": "^4.24.0", - "sinon": "^18.0.1", - "typescript": "^5.6.2", - "webpack": "^5.95.0", - "webpack-cli": "^5.1.4" + "rollup": "^4.34.6", + "sinon": "^19.0.2", + "typescript": "^5.7.3", + "webpack": "^5.97.1", + "webpack-cli": "^6.0.1" }, "optionalDependencies": { "debug": "^4.3.1" }, "engines": { - "node": ">=12" + "node": ">=18" }, "c4uIgnore": { "chalk": "^4.0.0 // ^5 is ESM only and won't work with transpiled version" diff --git a/src/Format.js b/src/Format.js index e27343f..7f7f024 100644 --- a/src/Format.js +++ b/src/Format.js @@ -10,22 +10,22 @@ export class Format { /** * @param {FormatOption} [opts] */ - constructor (opts) { + constructor(opts) { const { spaces } = opts || {} this.opts = { spaces } this._formatOpts() } - get spaces () { + get spaces() { return this.opts.spaces } - set spaces (spaces) { + set spaces(spaces) { this.opts.spaces = spaces this._formatOpts() } - _formatOpts () { + _formatOpts() { /** * @param {any} any * @returns {string} @@ -42,7 +42,7 @@ export class Format { * @param {...any} args * @returns {string} */ - stringify (...args) { + stringify(...args) { // @ts-expect-error return fastStringify(...args) } @@ -54,7 +54,7 @@ export class Format { * @param {any} obj * @return {Array} first is formatted message, other args may follow */ - format (fmt, args, obj) { + format(fmt, args, obj) { return quickFormat(fmt, args, this.formatOpts, obj) } } diff --git a/src/LogBase.js b/src/LogBase.js index be71aab..1056b67 100644 --- a/src/LogBase.js +++ b/src/LogBase.js @@ -2,13 +2,13 @@ import { Format } from './Format.js' import { toNumLevel, adjustLevel, LEVELS, LOG, INFO, FATAL } from './utils.js' import { Namespaces } from './Namespaces.js' -const noop = (...args) => {} +const noop = (..._args) => {} /** @typedef {'epoch'|'unix'|'iso'} Timestamp */ const time = { epoch: () => Date.now(), - unix: () => Date.now() / 1000 | 0, + unix: () => (Date.now() / 1000) | 0, iso: () => new Date().toISOString() } @@ -35,21 +35,23 @@ export class LogBase { * @param {string} name * @param {LogBaseOptions} opts */ - constructor (name, opts = {}) { + constructor(name, opts = {}) { this.name = name this.opts = opts this._enabled = {} this.formatter = new Format(opts) /** @type {{ [x: string]: (arg0: any) => any; } | null} */ - this.serializers = Object.entries(this.opts.serializers || {}) - .reduce((/** @type {object} */ curr, [key, val]) => { + this.serializers = Object.entries(this.opts.serializers || {}).reduce( + (/** @type {object} */ curr, [key, val]) => { if (typeof val === 'function') { curr = curr || {} curr[key] = val } return curr - }, null) + }, + null + ) this._timeF = time[opts.timestamp] this._time = this._timeF ? this._timeF : noop @@ -82,26 +84,25 @@ export class LogBase { /** * @param {string} [namespaces] */ - enable (namespaces = this.opts.namespaces) { + enable(namespaces = this.opts.namespaces) { const namespace = new Namespaces(namespaces) this._enabled = {} // reset const level = namespace.isEnabled(this.name, this.opts.level) - const active = level - ? LEVELS[adjustLevel(level, INFO)] - : [] - LEVELS.TRACE.forEach(level => { + const active = level ? LEVELS[adjustLevel(level, INFO)] : [] + LEVELS.TRACE.forEach((level) => { const nlevel = this.opts.levelNumbers ? toNumLevel(level) : level const llevel = level.toLowerCase() if (active.includes(level)) { this._enabled[level] = true - this[llevel] = level === FATAL - ? (fmt, ...args) => { - const str = this._log(nlevel, fmt, args) - // @ts-expect-error - this.flush && this.flush() - return str - } - : (fmt, ...args) => this._log(nlevel, fmt, args) + this[llevel] = + level === FATAL + ? (fmt, ...args) => { + const str = this._log(nlevel, fmt, args) + // @ts-expect-error + this.flush && this.flush() + return str + } + : (fmt, ...args) => this._log(nlevel, fmt, args) } else { this[llevel] = noop } @@ -110,16 +111,17 @@ export class LogBase { this.log = (fmt, ...args) => this._log(nLOG, fmt, args) } - get enabled () { - return this._enabled._cache || ( - this._enabled._cache = LEVELS.TRACE.reduce((o, level) => { + get enabled() { + return ( + this._enabled._cache || + (this._enabled._cache = LEVELS.TRACE.reduce((o, level) => { o[level] = o[level.toLowerCase()] = !!this._enabled[level] return o - }, {}) + }, {})) ) } - diff () { + diff() { const curr = Date.now() const prev = this._prev || curr this._prev = curr @@ -129,7 +131,7 @@ export class LogBase { /** * @return {object} json object */ - _formatJson (level, fmt, args = []) { + _formatJson(level, fmt, args = []) { const other = {} const msg = this.formatter.format(fmt, args, other) || undefined @@ -147,11 +149,14 @@ export class LogBase { return o } - _applySerializers (obj) { + _applySerializers(obj) { const o = {} for (const key in obj) { const value = obj[key] - if (Object.prototype.hasOwnProperty.call(obj, key) && value !== undefined) { + if ( + Object.prototype.hasOwnProperty.call(obj, key) && + value !== undefined + ) { if (this.serializers && this.serializers[key]) { o[key] = this.serializers[key](value) } else { @@ -163,13 +168,13 @@ export class LogBase { } /* c8 ignore next */ - _serverinfo () { } + _serverinfo() {} /** * @protected */ /* c8 ignore next 3 */ - _log (nlevel, fmt, args) { + _log(_nlevel, _fmt, _args) { throw new Error('needs implementation') } } diff --git a/src/Namespaces.js b/src/Namespaces.js index 89e398c..89d4a2c 100644 --- a/src/Namespaces.js +++ b/src/Namespaces.js @@ -10,7 +10,7 @@ const LEVELS = [TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF] const LEVELS_REGEX = RegExp(`^(${LEVELS.join('|')}):`, 'i') export class Namespaces { - constructor (namespaces) { + constructor(namespaces) { this.skips = [] this.names = [] this.enable(namespaces) @@ -19,14 +19,13 @@ export class Namespaces { /** * @param {string} namespaces */ - enable (namespaces) { + enable(namespaces) { this.skips = [] this.names = [] - const splited = (typeof namespaces === 'string' - ? namespaces - : '' - ).split(/[\s,]+/) + const splited = (typeof namespaces === 'string' ? namespaces : '').split( + /[\s,]+/ + ) for (const _namespace of splited) { if (!_namespace) continue // ignore empty strings @@ -39,18 +38,20 @@ export class Namespaces { } // sort names by levels - this.names = this.names.sort((a, b) => LEVELS.indexOf(a.level) - LEVELS.indexOf(b.level)) + this.names = this.names.sort( + (a, b) => LEVELS.indexOf(a.level) - LEVELS.indexOf(b.level) + ) } /* c8 ignore next 3 */ - disable () { + disable() { this.enable('') } /** * @param {string} name */ - isEnabled (name, level) { + isEnabled(name, level) { if (name === '*') { return level || 'DEBUG' } @@ -74,11 +75,9 @@ export class Namespaces { * @param {string} _namespace * @private */ - _namespaceNLevel (_namespace) { + _namespaceNLevel(_namespace) { const level = (LEVELS_REGEX.exec(_namespace) || [])[1] - const namespace = _namespace - .replace(LEVELS_REGEX, '') - .replace(/\*/g, '.*?') + const namespace = _namespace.replace(LEVELS_REGEX, '').replace(/\*/g, '.*?') return { namespace, level } } } diff --git a/src/Sonic.js b/src/Sonic.js index d89063c..3cd86fb 100644 --- a/src/Sonic.js +++ b/src/Sonic.js @@ -23,7 +23,7 @@ export class Sonic { * @param {NodeJS.WriteStream} stream * @param {SonicOptions} opts */ - constructor (stream, opts = {}) { + constructor(stream, opts = {}) { const { minLength = 4096, timeout = 1000 } = opts this._timer = undefined this._timeout = timeout @@ -44,7 +44,7 @@ export class Sonic { * @param {string} data * @returns {boolean} */ - write (data) { + write(data) { const isWritten = this.stream.write(data) if (!this._timer) { @@ -57,19 +57,19 @@ export class Sonic { return isWritten } - flush () { + flush() { // @ts-expect-error if (!this.stream.destroyed) { this.stream.flushSync() } } - destroy () { + destroy() { this.stream.destroy() } } -function filterBrokenPipe (stream, err) { +function filterBrokenPipe(stream, err) { if (err.code === 'EPIPE') { // If we get EPIPE, we should stop logging here // however we have no control to the consumer of @@ -91,7 +91,7 @@ export class SonicStreams extends Map { * @param {Record} opts * @returns {string} */ - static hash (opts) { + static hash(opts) { return ( 'sonic!' + Object.keys(opts || {}) @@ -106,7 +106,7 @@ export class SonicStreams extends Map { * @param {SonicOptions} [opts] * @returns {Sonic} */ - use (stream, opts = {}) { + use(stream, opts = {}) { const streamHash = SonicStreams.hash(streamDescriptor(stream)) const optsHash = SonicStreams.hash(opts) let streamRecord = this.get(streamHash) diff --git a/src/browser.js b/src/browser.js index 0674095..3c2d294 100644 --- a/src/browser.js +++ b/src/browser.js @@ -44,9 +44,11 @@ const options = { const storage = () => { try { // @ts-expect-error - return typeof chrome !== 'undefined' && typeof chrome.storage !== 'undefined' + return typeof chrome !== 'undefined' && // @ts-expect-error - ? chrome.storage.local + typeof chrome.storage !== 'undefined' + ? // @ts-expect-error + chrome.storage.local : window.localStorage } catch (err) { // istanbul ignore next @@ -66,18 +68,25 @@ const supportsColors = () => { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly - const isElectron = typeof window !== 'undefined' && + const isElectron = + typeof window !== 'undefined' && + (tmp = window.process) && // @ts-expect-error - (tmp = window.process) && (tmp.type === 'renderer') + tmp.type === 'renderer' // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - const isReactNative = typeof document !== 'undefined' && + const isReactNative = + typeof document !== 'undefined' && + (tmp = document.documentElement) && + (tmp = tmp.style) && // @ts-expect-error - (tmp = document.documentElement) && (tmp = tmp.style) && tmp.WebkitAppearance + tmp.WebkitAppearance // is firebug? http://stackoverflow.com/a/398120/376773 - const isFireBug = typeof window !== 'undefined' && + const isFireBug = + typeof window !== 'undefined' && + (tmp = window.console) && // @ts-expect-error - (tmp = window.console) && (tmp.firebug || (tmp.exception && tmp.table)) + (tmp.firebug || (tmp.exception && tmp.table)) if (isElectron) { // istanbul ignore next @@ -90,12 +99,14 @@ const supportsColors = () => { return false } - return !!(isReactNative || isFireBug || + return !!( + isReactNative || + isFireBug || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (/firefox\/(\d+)/i.exec(userAgent) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker - (/applewebkit\/(\d+)/i.exec(userAgent)) + /applewebkit\/(\d+)/i.exec(userAgent) ) } @@ -107,17 +118,18 @@ export class Log extends LogBase { * @param {string} name namespace of Logger * @param {LogOptionsBrowser} opts */ - constructor (name, opts) { + constructor(name, opts) { const _storage = storage() - Object.assign(options, - inspectOpts(_storage), - inspectNamespaces(_storage) - ) + Object.assign(options, inspectOpts(_storage), inspectNamespaces(_storage)) options.colors = options.colors === false ? false : supportsColors() - const serializers = Object.assign({}, options.serializers, opts?.serializers) + const serializers = Object.assign( + {}, + options.serializers, + opts?.serializers + ) const _opts = Object.assign({}, options, opts, { serializers }) super(name, _opts) @@ -135,8 +147,10 @@ export class Log extends LogBase { * @param {LogOptionsBrowser} [opts] changed options * @return {object} global options */ - static options (opts) { - if (!opts) { return Object.assign({}, options) } + static options(opts) { + if (!opts) { + return Object.assign({}, options) + } Object.assign(options, opts, { colors: opts.colors === false ? false : supportsColors() }) @@ -146,7 +160,7 @@ export class Log extends LogBase { /** * save options in `localStorage` */ - static save () { + static save() { const _storage = storage() Log.reset() saveOpts(_storage, options) @@ -155,7 +169,7 @@ export class Log extends LogBase { /** * reset saved options */ - static reset () { + static reset() { const _storage = storage() Object.keys(_storage).forEach((key) => { @@ -178,7 +192,7 @@ export class Log extends LogBase { * @param {LogOptionWrapConsole} [opts] * @return {function} unwrap function */ - static wrapConsole (name = 'console', opts = {}) { + static wrapConsole(name = 'console', opts = {}) { const log = new Log(name, opts) return wrapConsole(log, opts) } @@ -187,11 +201,11 @@ export class Log extends LogBase { * render arguments to console.log * @public * @param {any[]} args console.log arguments - * @param {Level} level level of log line (might be used for custom Logger which uses different streams per level) + * @param {Level} [_level] level of log line (might be used for custom Logger which uses different streams per level) * @return {any[]} */ - render (args, level) { - console.log(...args) // eslint-disable-line no-console + render(args, _level) { + console.log(...args) return args } @@ -201,7 +215,7 @@ export class Log extends LogBase { * @param {string} [fmt] formatter * @param {any[]} [args] log arguments */ - send (level, fmt, args) { + send(level, fmt, args) { let obj if (typeof level === 'object') { obj = level @@ -218,7 +232,7 @@ export class Log extends LogBase { * format log arguments * @protected */ - _log (level, fmt, args) { + _log(level, fmt, args) { const uns = this._formatJson(level, fmt, args) const obj = this._applySerializers(uns) const _args = this._format(obj) @@ -234,10 +248,12 @@ export class Log extends LogBase { /** * format arguments for console.log * @private - * @param {object} param0 + * @param {object} options * @return {Array} args for console.log */ - _format ({ level, name, time, msg = '', diff, ...other }) { + _format(options) { + // eslint-disable-next-line no-unused-vars + const { level, name, time, msg = '', diff, ...other } = options const color = this.color const args = [] const hasOther = Object.keys(other).length @@ -248,7 +264,9 @@ export class Log extends LogBase { msg, hasOther ? '%O' : undefined, this._color('+' + ms(diff)) - ].filter(s => s !== undefined).join(' ') + ] + .filter((s) => s !== undefined) + .join(' ') if (hasOther) args.push(other) if (this.opts.colors) { @@ -277,23 +295,24 @@ export class Log extends LogBase { * @param {string} str * @param {Function} [cb] */ - _sendLog (str, cb) { + _sendLog(str, cb) { const img = new Image() - const done = () => { cb && cb() } + const done = () => { + cb && cb() + } img.onload = done img.onerror = done img.onabort = done - img.src = this.opts.url + '?id=' + random(6) + '&log=' + encodeURIComponent(str) + img.src = + this.opts.url + '?id=' + random(6) + '&log=' + encodeURIComponent(str) } /** * Add colors, style to string * @private */ - _color (str) { - return this.opts.colors - ? `%c${str}%c` - : str + _color(str) { + return this.opts.colors ? `%c${str}%c` : str } } diff --git a/src/browserLogs.js b/src/browserLogs.js index 130147c..66f34dc 100644 --- a/src/browserLogs.js +++ b/src/browserLogs.js @@ -12,21 +12,21 @@ const gif = Buffer.from( * @param {string} url * @returns {object} */ -function parseQuery (url) { +function parseQuery(url) { // eslint-disable-next-line no-unused-vars const [path, search] = url.split('?') return Object.fromEntries(new URLSearchParams(search)) } class Loggers { - constructor (opts) { + constructor(opts) { const { maxSize = 100 } = opts || {} this.LogCls = opts?.Log || Log this.cache = new MapLRU(maxSize) } - get (name) { + get(name) { let log = this.cache.get(name) if (!log) { log = new this.LogCls(name) @@ -40,7 +40,7 @@ class Loggers { * @param {string|object} str * @returns {object} */ -function parseJson (str) { +function parseJson(str) { if (typeof str === 'object') { return str } @@ -70,7 +70,7 @@ function parseJson (str) { * @param {MwLogOption} [options] * @return {function} connect middleware */ -export function browserLogs (options) { +export function browserLogs(options) { const opts = { maxSize: 100, logAll: false, @@ -82,7 +82,7 @@ export function browserLogs (options) { const log = opts.logAll ? new LogCls('debug-level:browser') : undefined const loggers = new Loggers(opts) - return function _browserLogs (req, res) { + return function _browserLogs(req, res) { const query = req.query ? req.query : parseQuery(req.url) res.setHeader('Cache-Control', 'no-store, no-cache') diff --git a/src/ecs/LogEcs.js b/src/ecs/LogEcs.js index 541d077..7da0870 100644 --- a/src/ecs/LogEcs.js +++ b/src/ecs/LogEcs.js @@ -15,7 +15,7 @@ export class LogEcs extends Log { * @param {string} name logger namespace * @param {LogOptionsEcs} opts */ - constructor (name, opts) { + constructor(name, opts) { const { serializers, ..._opts } = opts || {} super(name, { ..._opts, @@ -28,7 +28,7 @@ export class LogEcs extends Log { } /* c8 ignore next 18 */ - _applySerializers (obj) { + _applySerializers(obj) { const ecsObj = {} for (const key in obj) { const value = obj[key] @@ -49,7 +49,7 @@ export class LogEcs extends Log { return ecsObj } - _toJson (obj, serializers) { + _toJson(obj, serializers) { const { level, time, name, msg, pid, hostname, diff, ...other } = obj const ecsObj = { diff --git a/src/ecs/serializers.js b/src/ecs/serializers.js index 1e8dbf1..65885cf 100644 --- a/src/ecs/serializers.js +++ b/src/ecs/serializers.js @@ -3,7 +3,7 @@ import { startTimeKey } from '../serializers/res.js' const isNotObject = (any) => !any || typeof any !== 'object' const ecsError = (err, ecsObj) => { - if (!(err?.message)) { + if (!err?.message) { return } @@ -58,12 +58,14 @@ const ecsReq = (req, ecsObj) => { const { method, httpVersion } = req if (!method) return + /* eslint-disable no-unused-vars */ const { cookie, authorization, 'user-agent': userAgent, ...headers } = req.headers || {} + /* eslint-enable no-unused-vars */ ecsObj.http = ecsObj.http || {} ecsObj.http.request = { @@ -84,6 +86,7 @@ const ecsRes = (res, ecsObj) => { const { statusCode } = res if (!statusCode) return + /* eslint-disable no-unused-vars */ const { 'proxy-authenticate': _1, 'set-cookie': _2, @@ -91,6 +94,7 @@ const ecsRes = (res, ecsObj) => { cookie, ...headers } = res.getHeaders() || {} + /* eslint-enable no-unused-vars */ ecsObj.http = ecsObj.http || {} ecsObj.http.response = { diff --git a/src/httpLogs.js b/src/httpLogs.js index 260f7ec..ac66344 100644 --- a/src/httpLogs.js +++ b/src/httpLogs.js @@ -33,7 +33,7 @@ const serializers = { * @param {LogOptionsHttpLog} [opts] * @returns {(req: IncomingMessageWithId, res: ServerResponse, next: Function) => void} connect middleware */ -export function httpLogs (namespace, opts) { +export function httpLogs(namespace, opts) { const options = { Log, ...opts @@ -47,7 +47,7 @@ export function httpLogs (namespace, opts) { const log = new options.Log(namespace || 'debug-level:http', options) const generateId = options.customGenerateRequestId || generateRequestId - return function _httpLogs (req, res, next) { + return function _httpLogs(req, res, next) { if (!req.id) { req.id = generateId() } diff --git a/src/logger.js b/src/logger.js index 7f738ea..bb27cba 100644 --- a/src/logger.js +++ b/src/logger.js @@ -10,7 +10,7 @@ const loggers = {} * @param {string} namespace * @param {LogOptions} [opts] */ -export function logger (namespace, opts) { +export function logger(namespace, opts) { const { Log: optsLog, ..._opts } = opts || {} const LogCls = optsLog || Log diff --git a/src/node.js b/src/node.js index 3f0aeb1..995eb7d 100644 --- a/src/node.js +++ b/src/node.js @@ -81,7 +81,7 @@ export class Log extends LogBase { * @param {String} name - namespace of Logger * @param {LogOptions} [opts] - see Log.options */ - constructor (name, opts) { + constructor(name, opts) { Object.assign( options, inspectOpts(process.env), @@ -108,9 +108,9 @@ export class Log extends LogBase { this.stream = this.opts.sonic ? sonicStreams.use(this.opts.stream, { - minLength: this.opts.sonicLength, - timeout: this.opts.sonicFlushMs - }) + minLength: this.opts.sonicLength, + timeout: this.opts.sonicFlushMs + }) : this.opts.stream || process.stderr if (!this.opts.json) { @@ -132,7 +132,7 @@ export class Log extends LogBase { * @param {object} [opts] changed options * @return {object} global options */ - static options (opts) { + static options(opts) { if (!opts) { return { ...options } } @@ -142,7 +142,7 @@ export class Log extends LogBase { /** * save options in `process.env` */ - static save () { + static save() { Log.reset() saveOpts(process.env, options) } @@ -150,7 +150,7 @@ export class Log extends LogBase { /** * reset saved options */ - static reset () { + static reset() { Object.keys(process.env).forEach((key) => { if (/^(DEBUG|DEBUG_.*)$/.test(key)) { delete process.env[key] @@ -165,7 +165,7 @@ export class Log extends LogBase { * @param {LogOptionWrapConsole} [opts] options * @return {function} unwrap function */ - static wrapConsole (name = 'console', opts) { + static wrapConsole(name = 'console', opts) { const log = new Log(name, opts) return wrapConsole(log, opts) } @@ -176,7 +176,7 @@ export class Log extends LogBase { * @param {string} [name='exit'] * @param {LogOptionHandleExitEvents} [opts] options */ - static handleExitEvents (name = 'exit', opts = {}) { + static handleExitEvents(name = 'exit', opts = {}) { const { code = 1, gracefulExit, ..._opts } = opts const log = new Log(name, _opts) EXIT_EVENTS.forEach((ev) => { @@ -194,7 +194,7 @@ export class Log extends LogBase { }) } - static wrapDebug () { + static wrapDebug() { return wrapDebug(Log) } @@ -202,15 +202,15 @@ export class Log extends LogBase { * render string to output stream * @public * @param {String} str string to render - * @param {String} level level of log line (might be used for custom Logger which uses different streams per level) + * @param {String} [_level] level of log line (might be used for custom Logger which uses different streams per level) * @return {String} */ - render (str, level) { + render(str, _level) { this.stream.write(flatstr(str + '\n')) return str } - flush () { + flush() { // @ts-expect-error this.stream.flush && this.stream.flush() } @@ -219,7 +219,7 @@ export class Log extends LogBase { * format object to json * @protected */ - _log (level, fmt, args) { + _log(level, fmt, args) { const o = this._formatJson(level, fmt, args) const str = this.toJson(o, this.serializers) return this.render(str, level) @@ -229,7 +229,7 @@ export class Log extends LogBase { * format object to json * @private */ - _logJsonColor (level, fmt, args) { + _logJsonColor(level, fmt, args) { const o = this._formatJson(level, fmt, args) let str = this.toJson(o, this.serializers) /* c8 ignore next 4 */ // can't cover with tests as underlying tty is unknown @@ -248,9 +248,11 @@ export class Log extends LogBase { * debug like output if `this.opts.json === false` * @private */ - _logDebugLike (_level, fmt, args) { + _logDebugLike(_level, fmt, args) { const o = this._formatJson(_level, fmt, args) + /* eslint-disable no-unused-vars */ const { level, time, name, msg, pid, hostname, diff, ...other } = o + /* eslint-enable no-unused-vars */ const prefix = ' ' + @@ -260,9 +262,9 @@ export class Log extends LogBase { const strOther = Object.keys(other).length ? stringify( - this._applySerializers(other), - this.opts.splitLine ? this.opts.spaces ?? 2 : undefined - ) + this._applySerializers(other), + this.opts.splitLine ? (this.opts.spaces ?? 2) : undefined + ) : '' const str = this.opts.splitLine @@ -297,7 +299,7 @@ export class Log extends LogBase { * Add colors, style to string * @private */ - _color (str, color, isBold) { + _color(str, color, isBold) { return !this.opts.colors ? str : isBold ? color.bold(str) : color(str) } } @@ -318,7 +320,7 @@ Log.serializers = { * @param {string} str * @returns {string} */ -function asString (str) { +function asString(str) { let result = '' let last = 0 let found = false @@ -349,7 +351,7 @@ function asString (str) { * @param {number} [spaces] * @returns {string} */ -function toJson (obj, serializers, spaces) { +function toJson(obj, serializers, spaces) { let s = '{' let comma = '' for (const key in obj) { @@ -387,7 +389,7 @@ function toJson (obj, serializers, spaces) { * @param {number} [spaces] * @returns {string} */ -export function stringify (any, spaces) { +export function stringify(any, spaces) { try { return JSON.stringify(any, null, spaces) } catch (e) { @@ -400,6 +402,6 @@ export function stringify (any, spaces) { * @param {string} str * @returns {string} */ -function replaceLf (str = '') { +function replaceLf(str = '') { return str.replace(/[\r\n]/g, '\\n') } diff --git a/src/quick-format.js b/src/quick-format.js index 020ff3e..dca9b4f 100644 --- a/src/quick-format.js +++ b/src/quick-format.js @@ -4,11 +4,15 @@ * @copyright Copyright (c) 2016-2019 David Mark Clements */ -function tryStringify (value, replacer, spaces) { - try { return JSON.stringify(value, replacer, spaces) } catch (e) { return '"[Circular]"' } +function tryStringify(value, replacer, spaces) { + try { + return JSON.stringify(value, replacer, spaces) + } catch (e) { + return '"[Circular]"' + } } -export function format (f, args, opts, obj = {}) { +export function format(f, args, opts, obj = {}) { const stringify = opts?.stringify || tryStringify const spaces = opts?.spaces const argLen = args.length @@ -20,10 +24,11 @@ export function format (f, args, opts, obj = {}) { if (Array.isArray(val)) { Object.assign(obj, { arr: val }) } else if (val instanceof Error) { - // } else if (val.stack && val.message && val.name) { + // } else if (val.stack && val.message && val.name) { if (!str) str = val.message Object.assign(obj, { err: val }) } else { + // eslint-disable-next-line no-unused-vars const { name, level, ...other } = val Object.assign(obj, other) } @@ -41,34 +46,47 @@ export function format (f, args, opts, obj = {}) { let lastPos = -1 const flen = (f && f.length) || 0 - for (let i = 0; i < flen;) { + for (let i = 0; i < flen; ) { if (f.charCodeAt(i) === 37 && i + 1 < flen) { lastPos = lastPos > -1 ? lastPos : 0 switch (f.charCodeAt(i + 1)) { case 100: // 'd' case 102: // 'f' - if (a >= argLen) { break } - if (lastPos < i) { str += f.slice(lastPos, i) } + if (a >= argLen) { + break + } + if (lastPos < i) { + str += f.slice(lastPos, i) + } if (args[a] == null) break str += Number(args[a]) lastPos = i = i + 2 break case 105: // 'i' - if (a >= argLen) { break } - if (lastPos < i) { str += f.slice(lastPos, i) } + if (a >= argLen) { + break + } + if (lastPos < i) { + str += f.slice(lastPos, i) + } if (args[a] == null) break str += Math.floor(Number(args[a])) lastPos = i = i + 2 break case 79: // 'O' case 111: // 'o' - case 106: { // 'j' - if (a >= argLen) { break } - if (lastPos < i) { str += f.slice(lastPos, i) } + case 106: { + // 'j' + if (a >= argLen) { + break + } + if (lastPos < i) { + str += f.slice(lastPos, i) + } if (args[a] === undefined) break const type = typeof args[a] if (type === 'string') { - str += '\'' + args[a] + '\'' + str += "'" + args[a] + "'" lastPos = i + 2 i++ break @@ -85,14 +103,20 @@ export function format (f, args, opts, obj = {}) { break } case 115: // 's' - if (a >= argLen) { break } - if (lastPos < i) { str += f.slice(lastPos, i) } + if (a >= argLen) { + break + } + if (lastPos < i) { + str += f.slice(lastPos, i) + } str += String(args[a]) lastPos = i + 2 i++ break case 37: // '%' - if (lastPos < i) { str += f.slice(lastPos, i) } + if (lastPos < i) { + str += f.slice(lastPos, i) + } str += '%' lastPos = i + 2 i++ diff --git a/src/serializers/err.js b/src/serializers/err.js index 6c240a2..4feb827 100644 --- a/src/serializers/err.js +++ b/src/serializers/err.js @@ -5,16 +5,17 @@ const circ = Symbol('circ') * @param {object} [err] * @returns {object} */ -export function errSerializer (err) { +export function errSerializer(err) { if (!(err instanceof Error)) { return err } const o = { msg: err.message, - name: Object.prototype.toString.call(err.constructor) === '[object Function]' - ? err.constructor.name - : err.name, + name: + Object.prototype.toString.call(err.constructor) === '[object Function]' + ? err.constructor.name + : err.name, stack: err.stack } err[circ] = undefined diff --git a/src/serializers/req.js b/src/serializers/req.js index 4dc90f7..bdf14ce 100644 --- a/src/serializers/req.js +++ b/src/serializers/req.js @@ -5,9 +5,10 @@ * @param {object} [req] * @returns {object} */ -export function reqSerializer (req) { +export function reqSerializer(req) { if (typeof req !== 'object' || !req) return + // eslint-disable-next-line no-unused-vars const { authorization, cookie, ...headers } = req.headers || {} const logReq = { @@ -31,7 +32,7 @@ export function reqSerializer (req) { * @param {object} [req] * @returns {object} */ -export function reqMaskSerializer (req) { +export function reqMaskSerializer(req) { const logReq = reqSerializer(req) if (!logReq) return @@ -57,7 +58,7 @@ export function reqMaskSerializer (req) { * @param {string} cookie * @returns {string} */ -function maskCookieVal (cookie) { +function maskCookieVal(cookie) { let masked = '' const len = cookie.length let mask = false diff --git a/src/serializers/res.js b/src/serializers/res.js index d87fe17..7167ba9 100644 --- a/src/serializers/res.js +++ b/src/serializers/res.js @@ -10,14 +10,16 @@ const PROXY_AUTHENTICATE = 'proxy-authenticate' * @param {object} [res] * @returns {object} */ -export function resSerializer (res) { +export function resSerializer(res) { if (typeof res !== 'object' || !res) return + /* eslint-disable no-unused-vars */ const { [SET_COOKIE]: _1, [PROXY_AUTHENTICATE]: _2, ...headers } = res.getHeaders() || {} + /* eslint-enable no-unused-vars */ const logRes = { statusCode: res.statusCode @@ -39,7 +41,7 @@ export function resSerializer (res) { * @param {object} [res] * @returns {object} */ -export function resMaskSerializer (res) { +export function resMaskSerializer(res) { const logRes = resSerializer(res) if (!logRes) return @@ -67,7 +69,7 @@ export function resMaskSerializer (res) { * @param {string} cookie * @returns {string} */ -function maskCookieVal (cookie) { +function maskCookieVal(cookie) { let masked = '' const len = cookie.length let mask = false diff --git a/src/utils.js b/src/utils.js index ca02bd8..63eeebc 100644 --- a/src/utils.js +++ b/src/utils.js @@ -33,16 +33,43 @@ export const LEVELS = { } export const COLORS = [ - '#6600FF', '#3333FF', '#3333CC', '#0066FF', - '#0066CC', '#0066FF', - '#006633', '#006666', '#006600', - '#00CC00', '#00CC33', '#00CC66', '#00CC99', - '#009900', '#009933', '#009966', '#009999', - '#00CCFF', '#00CCCC', - '#FF9900', '#FF9933', '#FF6600', '#FF6633', - '#FF0000', '#FF0033', '#FF3300', '#FF3300', '#FF3333', - '#CC0000', '#CC0033', '#CC0066', '#FF0066', '#FF3366', - '#FF00FF', '#FF33FF', '#CC00CC', '#990099' + '#6600FF', + '#3333FF', + '#3333CC', + '#0066FF', + '#0066CC', + '#0066FF', + '#006633', + '#006666', + '#006600', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#009900', + '#009933', + '#009966', + '#009999', + '#00CCFF', + '#00CCCC', + '#FF9900', + '#FF9933', + '#FF6600', + '#FF6633', + '#FF0000', + '#FF0033', + '#FF3300', + '#FF3300', + '#FF3333', + '#CC0000', + '#CC0033', + '#CC0066', + '#FF0066', + '#FF3366', + '#FF00FF', + '#FF33FF', + '#CC00CC', + '#990099' ] export const LEVEL_COLORS = { @@ -96,40 +123,44 @@ export const fromNumLevel = (level) => { * @copyright debug contributors * @see https://github.com/visionmedia/debug */ -export const inspectOpts = (obj) => Object.keys(obj) - .filter((key) => /^debug_/i.test(key)) - .reduce((opts, key) => { - // camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }) - - // coerce string value into JS value - let val = obj[key] - if (/^(yes|on|true|enabled)$/i.test(val)) val = true - else if (/^(no|off|false|disabled)$/i.test(val)) val = false - else if (val === 'null') val = null - else val = Number(val) - - if (prop === 'stream' || prop === 'formatters') { - // do nothing - } else if (prop === 'level') { - val = adjustLevel(obj[key]) - if (val) opts[prop] = val - } else if (prop === 'url' || prop === 'timestamp') { - opts[prop] = obj[key] - } else { - opts[prop] = val - } +export const inspectOpts = (obj) => + Object.keys(obj) + .filter((key) => /^debug_/i.test(key)) + .reduce((opts, key) => { + // camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { + return k.toUpperCase() + }) + + // coerce string value into JS value + let val = obj[key] + if (/^(yes|on|true|enabled)$/i.test(val)) val = true + else if (/^(no|off|false|disabled)$/i.test(val)) val = false + else if (val === 'null') val = null + else val = Number(val) + + if (prop === 'stream' || prop === 'formatters') { + // do nothing + } else if (prop === 'level') { + val = adjustLevel(obj[key]) + if (val) opts[prop] = val + } else if (prop === 'url' || prop === 'timestamp') { + opts[prop] = obj[key] + } else { + opts[prop] = val + } - return opts - }, {}) + return opts + }, {}) export const saveOpts = (obj, options) => { Object.keys(options).forEach((prop) => { if (['stream', 'serializers', 'toJson'].includes(prop)) return // do not safe stream option - let key = 'DEBUG_' + prop.replace(/([A-Z])/g, (_, prop) => '_' + prop.toLowerCase()) + let key = + 'DEBUG_' + prop.replace(/([A-Z])/g, (_, prop) => '_' + prop.toLowerCase()) if (prop === 'namespaces') key = 'DEBUG' key = key.toUpperCase() obj[key] = options[prop] @@ -140,7 +171,7 @@ export const selectColor = (namespace, fn) => { let hash = 0 for (const i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i) + hash = (hash << 5) - hash + namespace.charCodeAt(i) hash |= 0 // Convert to 32bit integer } @@ -150,11 +181,10 @@ export const selectColor = (namespace, fn) => { } export const levelColors = (fn) => { - const colors = Object.keys(LEVEL_COLORS) - .reduce((colors, level) => { - colors[level] = fn(LEVEL_COLORS[level]) - return colors - }, {}) + const colors = Object.keys(LEVEL_COLORS).reduce((colors, level) => { + colors[level] = fn(LEVEL_COLORS[level]) + return colors + }, {}) return colors } @@ -163,4 +193,5 @@ export const inspectNamespaces = (obj) => { if (namespaces) return { namespaces } } -export const random = (len) => Math.random().toString(16).toLowerCase().slice(2, len) +export const random = (len) => + Math.random().toString(16).toLowerCase().slice(2, len) diff --git a/src/wrapConsole.js b/src/wrapConsole.js index 96ba700..3ce4e1d 100644 --- a/src/wrapConsole.js +++ b/src/wrapConsole.js @@ -6,7 +6,7 @@ let wrapped = null const unwrap = () => { if (wrapped) { - LEVELS.forEach(level => { + LEVELS.forEach((level) => { console[level] = wrapped[level] }) wrapped = null @@ -18,21 +18,21 @@ const unwrap = () => { * console.log, console.info, console.warn, console.error * @return unwrap function */ -export function wrapConsole (log, { level4log = 'LOG' } = {}) { +export function wrapConsole(log, { level4log = 'LOG' } = {}) { if (wrapped) return unwrap wrapped = {} const _level4log = adjustLevel(level4log, 'LOG').toLowerCase() - const render = level => (...args) => { - log[level](...args) - } + const render = + (level) => + (...args) => { + log[level](...args) + } - LEVELS.map(l => l.toLowerCase()).forEach(level => { + LEVELS.map((l) => l.toLowerCase()).forEach((level) => { wrapped[level] = console[level] - const renderLevel = level === 'log' - ? _level4log - : level + const renderLevel = level === 'log' ? _level4log : level console[level] = render(renderLevel) }) diff --git a/src/wrapDebug.js b/src/wrapDebug.js index f526603..ae7dcc7 100644 --- a/src/wrapDebug.js +++ b/src/wrapDebug.js @@ -4,21 +4,21 @@ let wrapped = null const unwrap = () => { if (wrapped) { - Object.keys(wrapped).forEach(key => { + Object.keys(wrapped).forEach((key) => { debug[key] = wrapped[key] }) wrapped = null } } -export function wrapDebug (Log) { +export function wrapDebug(Log) { if (wrapped) return unwrap class Loggers { - constructor () { + constructor() { this.cache = {} } - get (namespace) { + get(namespace) { let logger = this.cache[namespace] if (!logger) { logger = this.cache[namespace] = new Log(namespace) diff --git a/test/LogEcs.test.js b/test/LogEcs.test.js index 6f5882e..a2a1479 100644 --- a/test/LogEcs.test.js +++ b/test/LogEcs.test.js @@ -110,6 +110,7 @@ describe('LogEcs', function () { }) it('shall serialize a request with originalUrl', function () { + // eslint-disable-next-line no-unused-vars const { host, ...headers } = req.headers const _req = { ...req, @@ -235,7 +236,12 @@ describe('LogEcs', function () { before(() => { clock = sinon.useFakeTimers() - LogEcs.options({ level: 'error', json: false, colors: false, namespaces: 'test*' }) + LogEcs.options({ + level: 'error', + json: false, + colors: false, + namespaces: 'test*' + }) log = new LogEcs('test', { timestamp: 'iso' }) }) diff --git a/test/Sonic.test.js b/test/Sonic.test.js index 0e3752b..6b742e6 100644 --- a/test/Sonic.test.js +++ b/test/Sonic.test.js @@ -27,7 +27,7 @@ describe('Sonic', function () { it('shall throw if no stream is setup', function () { assert.throws(() => { - new Sonic() // eslint-disable-line no-new + new Sonic() }, /TypeError: Cannot destructure property/) }) @@ -60,7 +60,8 @@ describe('Sonic', function () { }) it('broken pipe', async function () { - const sleep = (ms = 1) => new Promise((resolve) => setTimeout(() => resolve(), ms)) + const sleep = (ms = 1) => + new Promise((resolve) => setTimeout(() => resolve(), ms)) const fsStream = fs.createWriteStream('/dev/null') const stream = new Sonic(fsStream) diff --git a/test/browser.test.js b/test/browser.test.js index 599656f..d546779 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -46,7 +46,12 @@ bdescribe('#Log', function () { }) it('should set options', function () { - Log.options({ level: 'error', colors: false, url: 'http://localhost:3000/log', namespaces: 'foo*,bar' }) + Log.options({ + level: 'error', + colors: false, + url: 'http://localhost:3000/log', + namespaces: 'foo*,bar' + }) const res = Log.options() assert.deepStrictEqual(res, { level: 'error', @@ -57,7 +62,12 @@ bdescribe('#Log', function () { }) it('should save options', function () { - Log.options({ level: 'ERROR', url: undefined, colors: true, namespaces: 'foo*,bar' }) + Log.options({ + level: 'ERROR', + url: undefined, + colors: true, + namespaces: 'foo*,bar' + }) Log.save() const store = window.localStorage const res = Object.keys(store) @@ -80,12 +90,12 @@ bdescribe('#Log', function () { const tests = [ [undefined, { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - ['DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - ['INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], - ['WARN', { fatal: 1, error: 1, warn: 1 }], - ['ERROR', { fatal: 1, error: 1 }], - ['FATAL', { fatal: 1 }], - ['OFF', {}] + ['DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], + ['INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], + ['WARN', { fatal: 1, error: 1, warn: 1 }], + ['ERROR', { fatal: 1, error: 1 }], + ['FATAL', { fatal: 1 }], + ['OFF', {}] ] tests.forEach(([level, expects]) => { it('shall display logs for level ' + level, function () { @@ -116,12 +126,12 @@ bdescribe('#Log', function () { const tests = [ [undefined, {}], - ['DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - ['INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], - ['WARN', { fatal: 1, error: 1, warn: 1 }], - ['ERROR', { fatal: 1, error: 1 }], - ['FATAL', { fatal: 1 }], - ['OFF', {}] + ['DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], + ['INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], + ['WARN', { fatal: 1, error: 1, warn: 1 }], + ['ERROR', { fatal: 1, error: 1 }], + ['FATAL', { fatal: 1 }], + ['OFF', {}] ] tests.forEach(([level, expects]) => { it('shall display logs for level ' + level, function () { @@ -152,20 +162,24 @@ bdescribe('#Log', function () { const tests = [ // level, nsLevel, expects - [undefined, undefined, { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - [undefined, 'DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - [undefined, 'INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], - [undefined, 'WARN', { fatal: 1, error: 1, warn: 1 }], - [undefined, 'ERROR', { fatal: 1, error: 1 }], - [undefined, 'FATAL', { fatal: 1 }], - [undefined, 'OFF', {}], - ['ERROR', undefined, { fatal: 1, error: 1 }], - ['ERROR', 'DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - ['ERROR', 'INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], - ['ERROR', 'WARN', { fatal: 1, error: 1, warn: 1 }], - ['ERROR', 'ERROR', { fatal: 1, error: 1 }], - ['FATAL', 'FATAL', { fatal: 1 }], - ['ERROR', 'OFF', {}] + [ + undefined, + undefined, + { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 } + ], + [undefined, 'DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], + [undefined, 'INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], + [undefined, 'WARN', { fatal: 1, error: 1, warn: 1 }], + [undefined, 'ERROR', { fatal: 1, error: 1 }], + [undefined, 'FATAL', { fatal: 1 }], + [undefined, 'OFF', {}], + ['ERROR', undefined, { fatal: 1, error: 1 }], + ['ERROR', 'DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], + ['ERROR', 'INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], + ['ERROR', 'WARN', { fatal: 1, error: 1, warn: 1 }], + ['ERROR', 'ERROR', { fatal: 1, error: 1 }], + ['FATAL', 'FATAL', { fatal: 1 }], + ['ERROR', 'OFF', {}] ] tests.forEach(([level, nsLevel, expects]) => { it(`shall display logs for level ${level} using namespaced-level ${nsLevel}`, function () { @@ -197,12 +211,30 @@ bdescribe('#Log', function () { after(reset) const tests = [ - ['DEBUG', { fatal: true, error: true, warn: true, info: true, debug: true }], - ['INFO', { fatal: true, error: true, warn: true, info: true, debug: false }], - ['WARN', { fatal: true, error: true, warn: true, info: false, debug: false }], - ['ERROR', { fatal: true, error: true, warn: false, info: false, debug: false }], - ['FATAL', { fatal: true, error: false, warn: false, info: false, debug: false }], - ['OFF', { fatal: false, error: false, warn: false, info: false, debug: false }] + [ + 'DEBUG', + { fatal: true, error: true, warn: true, info: true, debug: true } + ], + [ + 'INFO', + { fatal: true, error: true, warn: true, info: true, debug: false } + ], + [ + 'WARN', + { fatal: true, error: true, warn: true, info: false, debug: false } + ], + [ + 'ERROR', + { fatal: true, error: true, warn: false, info: false, debug: false } + ], + [ + 'FATAL', + { fatal: true, error: false, warn: false, info: false, debug: false } + ], + [ + 'OFF', + { fatal: false, error: false, warn: false, info: false, debug: false } + ] ] tests.forEach(([level, exp]) => { it('shall check if enabled for level ' + level, function () { @@ -223,12 +255,13 @@ bdescribe('#Log', function () { describe('formats', function () { after(reset) - const fixErr = (args) => args.map(v => { - if (typeof v === 'object' && v.err) { - v.err = { name: 'Error' } - } - return v - }) + const fixErr = (args) => + args.map((v) => { + if (typeof v === 'object' && v.err) { + v.err = { name: 'Error' } + } + return v + }) describe('debug like', function () { const f = fixtures.browser @@ -252,14 +285,20 @@ bdescribe('#Log', function () { after(() => { clock.restore() if (WRITE) inspect(exp) - Object.keys(window.localStorage).forEach((i) => window.localStorage.removeItem(i)) + Object.keys(window.localStorage).forEach((i) => + window.localStorage.removeItem(i) + ) }) testcases.forEach(({ name, args }, idx) => { it(name, function () { const res = log.error(...args) if (WRITE) exp.push(res) - assert.deepStrictEqual(fixErr(res), fixErr(f[idx]), '[' + idx + '] ' + res + ' !== ' + f[idx]) + assert.deepStrictEqual( + fixErr(res), + fixErr(f[idx]), + '[' + idx + '] ' + res + ' !== ' + f[idx] + ) }) }) }) @@ -285,7 +324,11 @@ bdescribe('#Log', function () { it(name, function () { const res = log.error(...args) if (WRITE) exp.push(res) - assert.deepStrictEqual(fixErr(res), fixErr(f[idx]), '[' + idx + '] ' + res + ' !== ' + f[idx]) + assert.deepStrictEqual( + fixErr(res), + fixErr(f[idx]), + '[' + idx + '] ' + res + ' !== ' + f[idx] + ) }) }) }) @@ -325,12 +368,12 @@ bdescribe('#Log', function () { describe('namespace *', function () { const tests = [ [undefined, { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - ['DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - ['INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], - ['WARN', { fatal: 1, error: 1, warn: 1 }], - ['ERROR', { fatal: 1, error: 1 }], - ['FATAL', { fatal: 1 }], - ['OFF', {}] + ['DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], + ['INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], + ['WARN', { fatal: 1, error: 1, warn: 1 }], + ['ERROR', { fatal: 1, error: 1 }], + ['FATAL', { fatal: 1 }], + ['OFF', {}] ] tests.forEach(([level, expects]) => { it(`shall ${level === 'OFF' ? 'never' : 'always'} log for level ${level}`, function () { diff --git a/test/fixtures/Format.js b/test/fixtures/Format.js index 7779c1b..903ed23 100644 --- a/test/fixtures/Format.js +++ b/test/fixtures/Format.js @@ -1,5 +1,6 @@ const err = new TypeError('error message') -err.stack = 'TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile' // shortened stack +err.stack = + 'TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile' // shortened stack err.status = 500 export default { diff --git a/test/fixtures/browser.js b/test/fixtures/browser.js index 803e5ee..ad9d6ad 100644 --- a/test/fixtures/browser.js +++ b/test/fixtures/browser.js @@ -1,15 +1,12 @@ -import { - circular, - quotes, - custom -} from './testcases.js' +import { circular, quotes, custom } from './testcases.js' import { ua } from '../helpers/ua.js' const err = { err: { name: 'TypeError', message: 'error message', - stack: 'TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile', + stack: + 'TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile', status: 500 } } @@ -44,11 +41,17 @@ export default { ['ERROR test obj {"object":{"test":1},"msg":"the message"} +0ms'], ['ERROR test obj [1,2,3] +0ms'], ua === 'firefox' - ? ['ERROR test error {"stack":"TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile","status":500} +0ms'] + ? [ + 'ERROR test error {"stack":"TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile","status":500} +0ms' + ] : ['ERROR test error {"status":500} +0ms'], ua === 'firefox' - ? ['ERROR test mixed % string 1.1 2.2 3.33 {"object":{"test":1},"msg":"the message"} {"stack":"TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile","status":500} +0ms'] - : ['ERROR test mixed % string 1.1 2.2 3.33 {"object":{"test":1},"msg":"the message"} {"status":500} +0ms'], + ? [ + 'ERROR test mixed % string 1.1 2.2 3.33 {"object":{"test":1},"msg":"the message"} {"stack":"TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile","status":500} +0ms' + ] + : [ + 'ERROR test mixed % string 1.1 2.2 3.33 {"object":{"test":1},"msg":"the message"} {"status":500} +0ms' + ], ['ERROR test error message %s %% %d string 1.1 %O +0ms', err], ['ERROR test the message %O +0ms', { ...err, ...obj }], ['ERROR test the message %O +0ms', { ...err, ...obj }], @@ -57,39 +60,307 @@ export default { ['ERROR test with level +0ms'] ], colors: [ - ['%cERROR%c %ctest%c string %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c 1 %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c false %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c the message %O %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', obj, 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c error message %O %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', err, 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c string %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c 1 %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c false %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c the message %O %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', obj, 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c the message %O %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', obj, 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c %O %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', { arr: [1, 2, 3] }, 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c error message %O %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', err, 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c %O %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', circular, 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c null %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c undefined %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c %d %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c %d %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c hello world %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c digit 42.7 %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c json {"object":{"test":1},"msg":"the message"} %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c obj {"object":{"test":1},"msg":"the message"} %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c obj [1,2,3] %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], + [ + '%cERROR%c %ctest%c string %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c 1 %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c false %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c the message %O %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + obj, + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c error message %O %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + err, + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c string %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c 1 %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c false %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c the message %O %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + obj, + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c the message %O %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + obj, + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c %O %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + { arr: [1, 2, 3] }, + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c error message %O %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + err, + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c %O %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + circular, + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c null %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c undefined %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c %d %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c %d %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c hello world %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c digit 42.7 %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c json {"object":{"test":1},"msg":"the message"} %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c obj {"object":{"test":1},"msg":"the message"} %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c obj [1,2,3] %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], ua === 'firefox' - ? ['%cERROR%c %ctest%c error {"stack":"TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile","status":500} %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'] - : ['%cERROR%c %ctest%c error {"status":500} %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], + ? [ + '%cERROR%c %ctest%c error {"stack":"TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile","status":500} %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ] + : [ + '%cERROR%c %ctest%c error {"status":500} %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], ua === 'firefox' - ? ['%cERROR%c %ctest%c mixed % string 1.1 2.2 3.33 {"object":{"test":1},"msg":"the message"} {"stack":"TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile","status":500} %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'] - : ['%cERROR%c %ctest%c mixed % string 1.1 2.2 3.33 {"object":{"test":1},"msg":"the message"} {"status":500} %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c error message %s %% %d string 1.1 %O %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', err, 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c the message %O %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', { ...err, ...obj }, 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c the message %O %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', { ...err, ...obj }, 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c %O %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', quotes, 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c %O %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', { req: custom }, 'color:#FF6600', 'color:inherit'], - ['%cERROR%c %ctest%c with level %c+0ms%c', 'color:#CC0000', 'color:inherit', 'color:#FF6600;font-weight:bold', 'color:inherit', 'color:#FF6600', 'color:inherit'] + ? [ + '%cERROR%c %ctest%c mixed % string 1.1 2.2 3.33 {"object":{"test":1},"msg":"the message"} {"stack":"TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile","status":500} %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ] + : [ + '%cERROR%c %ctest%c mixed % string 1.1 2.2 3.33 {"object":{"test":1},"msg":"the message"} {"status":500} %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c error message %s %% %d string 1.1 %O %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + err, + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c the message %O %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + { ...err, ...obj }, + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c the message %O %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + { ...err, ...obj }, + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c %O %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + quotes, + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c %O %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + { req: custom }, + 'color:#FF6600', + 'color:inherit' + ], + [ + '%cERROR%c %ctest%c with level %c+0ms%c', + 'color:#CC0000', + 'color:inherit', + 'color:#FF6600;font-weight:bold', + 'color:inherit', + 'color:#FF6600', + 'color:inherit' + ] ] } diff --git a/test/fixtures/logEcs.js b/test/fixtures/logEcs.js index 3807515..f55c0ec 100644 --- a/test/fixtures/logEcs.js +++ b/test/fixtures/logEcs.js @@ -4,81 +4,81 @@ export default { ' ERROR test 1970-01-01T00:00:00.001Z 1 +0ms', ' ERROR test 1970-01-01T00:00:00.002Z false +1ms', ' ERROR test 1970-01-01T00:00:00.003Z the message {\n' + - ' ERROR test "extra": {\n' + - ' ERROR test "test": {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test }\n' + - ' ERROR test }\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "extra": {\n' + + ' ERROR test "test": {\n' + + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test }\n' + + ' ERROR test }\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.004Z error message {\n' + - ' ERROR test "error": {\n' + - ' ERROR test "type": "TypeError",\n' + - ' ERROR test "message": "error message",\n' + - ' ERROR test "stack_trace": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile"\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "error": {\n' + + ' ERROR test "type": "TypeError",\n' + + ' ERROR test "message": "error message",\n' + + ' ERROR test "stack_trace": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile"\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.005Z string +1ms', ' ERROR test 1970-01-01T00:00:00.006Z 1 +1ms', ' ERROR test 1970-01-01T00:00:00.007Z false +1ms', ' ERROR test 1970-01-01T00:00:00.008Z the message {\n' + - ' ERROR test "extra": {\n' + - ' ERROR test "test": {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test }\n' + - ' ERROR test }\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "extra": {\n' + + ' ERROR test "test": {\n' + + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test }\n' + + ' ERROR test }\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.009Z the message {\n' + - ' ERROR test "extra": {\n' + - ' ERROR test "test": {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test }\n' + - ' ERROR test }\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "extra": {\n' + + ' ERROR test "test": {\n' + + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test }\n' + + ' ERROR test }\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.010Z {\n' + - ' ERROR test "extra": {\n' + - ' ERROR test "test": {\n' + - ' ERROR test "arr": [\n' + - ' ERROR test 1,\n' + - ' ERROR test 2,\n' + - ' ERROR test 3\n' + - ' ERROR test ]\n' + - ' ERROR test }\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "extra": {\n' + + ' ERROR test "test": {\n' + + ' ERROR test "arr": [\n' + + ' ERROR test 1,\n' + + ' ERROR test 2,\n' + + ' ERROR test 3\n' + + ' ERROR test ]\n' + + ' ERROR test }\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.011Z error message {\n' + - ' ERROR test "error": {\n' + - ' ERROR test "type": "TypeError",\n' + - ' ERROR test "message": "error message",\n' + - ' ERROR test "stack_trace": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile"\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "error": {\n' + + ' ERROR test "type": "TypeError",\n' + + ' ERROR test "message": "error message",\n' + + ' ERROR test "stack_trace": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile"\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.012Z {\n' + - ' ERROR test "extra": {\n' + - ' ERROR test "test": {\n' + - ' ERROR test "a": {\n' + - ' ERROR test "b": {\n' + - ' ERROR test "c": 1\n' + - ' ERROR test },\n' + - ' ERROR test "e": "[Circular]"\n' + - ' ERROR test },\n' + - ' ERROR test "d": {\n' + - ' ERROR test "a": {\n' + - ' ERROR test "b": {\n' + - ' ERROR test "c": 1\n' + - ' ERROR test },\n' + - ' ERROR test "e": "[Circular]"\n' + - ' ERROR test },\n' + - ' ERROR test "d": "[Circular]"\n' + - ' ERROR test }\n' + - ' ERROR test }\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "extra": {\n' + + ' ERROR test "test": {\n' + + ' ERROR test "a": {\n' + + ' ERROR test "b": {\n' + + ' ERROR test "c": 1\n' + + ' ERROR test },\n' + + ' ERROR test "e": "[Circular]"\n' + + ' ERROR test },\n' + + ' ERROR test "d": {\n' + + ' ERROR test "a": {\n' + + ' ERROR test "b": {\n' + + ' ERROR test "c": 1\n' + + ' ERROR test },\n' + + ' ERROR test "e": "[Circular]"\n' + + ' ERROR test },\n' + + ' ERROR test "d": "[Circular]"\n' + + ' ERROR test }\n' + + ' ERROR test }\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.013Z null +1ms', ' ERROR test 1970-01-01T00:00:00.014Z undefined +1ms', ' ERROR test 1970-01-01T00:00:00.015Z %d +1ms', @@ -86,89 +86,89 @@ export default { ' ERROR test 1970-01-01T00:00:00.017Z hello world +1ms', ' ERROR test 1970-01-01T00:00:00.018Z digit 42.7 +1ms', ' ERROR test 1970-01-01T00:00:00.019Z json {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test },\n' + - ' ERROR test "msg": "the message"\n' + - ' ERROR test } +1ms', + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test },\n' + + ' ERROR test "msg": "the message"\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.020Z obj {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test },\n' + - ' ERROR test "msg": "the message"\n' + - ' ERROR test } +1ms', + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test },\n' + + ' ERROR test "msg": "the message"\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.021Z obj [\n' + - ' ERROR test 1,\n' + - ' ERROR test 2,\n' + - ' ERROR test 3\n' + - ' ERROR test ] +1ms', + ' ERROR test 1,\n' + + ' ERROR test 2,\n' + + ' ERROR test 3\n' + + ' ERROR test ] +1ms', ' ERROR test 1970-01-01T00:00:00.022Z error {\n' + - ' ERROR test "status": 500\n' + - ' ERROR test } +1ms', + ' ERROR test "status": 500\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.023Z mixed % string 1.1 2.2 3.33 {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test },\n' + - ' ERROR test "msg": "the message"\n' + - ' ERROR test } {\n' + - ' ERROR test "status": 500\n' + - ' ERROR test } +1ms', + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test },\n' + + ' ERROR test "msg": "the message"\n' + + ' ERROR test } {\n' + + ' ERROR test "status": 500\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.024Z error message %s %% %d string 1.1 {\n' + - ' ERROR test "error": {\n' + - ' ERROR test "type": "TypeError",\n' + - ' ERROR test "message": "error message",\n' + - ' ERROR test "stack_trace": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile"\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "error": {\n' + + ' ERROR test "type": "TypeError",\n' + + ' ERROR test "message": "error message",\n' + + ' ERROR test "stack_trace": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile"\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.025Z the message {\n' + - ' ERROR test "error": {\n' + - ' ERROR test "type": "TypeError",\n' + - ' ERROR test "message": "error message",\n' + - ' ERROR test "stack_trace": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile"\n' + - ' ERROR test },\n' + - ' ERROR test "extra": {\n' + - ' ERROR test "test": {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test }\n' + - ' ERROR test }\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "error": {\n' + + ' ERROR test "type": "TypeError",\n' + + ' ERROR test "message": "error message",\n' + + ' ERROR test "stack_trace": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile"\n' + + ' ERROR test },\n' + + ' ERROR test "extra": {\n' + + ' ERROR test "test": {\n' + + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test }\n' + + ' ERROR test }\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.026Z the message {\n' + - ' ERROR test "extra": {\n' + - ' ERROR test "test": {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test }\n' + - ' ERROR test }\n' + - ' ERROR test },\n' + - ' ERROR test "error": {\n' + - ' ERROR test "type": "TypeError",\n' + - ' ERROR test "message": "error message",\n' + - ' ERROR test "stack_trace": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile"\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "extra": {\n' + + ' ERROR test "test": {\n' + + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test }\n' + + ' ERROR test }\n' + + ' ERROR test },\n' + + ' ERROR test "error": {\n' + + ' ERROR test "type": "TypeError",\n' + + ' ERROR test "message": "error message",\n' + + ' ERROR test "stack_trace": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile"\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.027Z {\n' + - ' ERROR test "extra": {\n' + - ' ERROR test "test": {\n' + - ' ERROR test "7123000": 7123000,\n' + - ' ERROR test "_abcdEF$01": "abcdef",\n' + - ' ERROR test "0.1234": 0.1234,\n' + - ' ERROR test "s p-a c e": "space",\n' + - ' ERROR test "\\"\'``\\"": "\\"\'``\\"",\n' + - ' ERROR test "\\"": "\\"",\n' + - ' ERROR test "\'": "\'"\n' + - ' ERROR test }\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "extra": {\n' + + ' ERROR test "test": {\n' + + ' ERROR test "7123000": 7123000,\n' + + ' ERROR test "_abcdEF$01": "abcdef",\n' + + ' ERROR test "0.1234": 0.1234,\n' + + ' ERROR test "s p-a c e": "space",\n' + + ' ERROR test "\\"\'``\\"": "\\"\'``\\"",\n' + + ' ERROR test "\\"": "\\"",\n' + + ' ERROR test "\'": "\'"\n' + + ' ERROR test }\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.028Z {\n' + - ' ERROR test "client": {\n' + - ' ERROR test "ip": "10.10.10.10"\n' + - ' ERROR test },\n' + - ' ERROR test "url": {\n' + - ' ERROR test "path": "/test"\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "client": {\n' + + ' ERROR test "ip": "10.10.10.10"\n' + + ' ERROR test },\n' + + ' ERROR test "url": {\n' + + ' ERROR test "path": "/test"\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.029Z with level +1ms' ], json: [ diff --git a/test/fixtures/node.js b/test/fixtures/node.js index b196d91..83834e8 100644 --- a/test/fixtures/node.js +++ b/test/fixtures/node.js @@ -4,63 +4,63 @@ export default { ' ERROR test 1970-01-01T00:00:00.001Z 1 +0ms', ' ERROR test 1970-01-01T00:00:00.002Z false +1ms', ' ERROR test 1970-01-01T00:00:00.003Z the message {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.004Z error message {\n' + - ' ERROR test "err": {\n' + - ' ERROR test "msg": "error message",\n' + - ' ERROR test "name": "TypeError",\n' + - ' ERROR test "stack": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile",\n' + - ' ERROR test "status": 500\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "err": {\n' + + ' ERROR test "msg": "error message",\n' + + ' ERROR test "name": "TypeError",\n' + + ' ERROR test "stack": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile",\n' + + ' ERROR test "status": 500\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.005Z string +1ms', ' ERROR test 1970-01-01T00:00:00.006Z 1 +1ms', ' ERROR test 1970-01-01T00:00:00.007Z false +1ms', ' ERROR test 1970-01-01T00:00:00.008Z the message {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.009Z the message {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.010Z {\n' + - ' ERROR test "arr": [\n' + - ' ERROR test 1,\n' + - ' ERROR test 2,\n' + - ' ERROR test 3\n' + - ' ERROR test ]\n' + - ' ERROR test } +1ms', + ' ERROR test "arr": [\n' + + ' ERROR test 1,\n' + + ' ERROR test 2,\n' + + ' ERROR test 3\n' + + ' ERROR test ]\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.011Z error message {\n' + - ' ERROR test "err": {\n' + - ' ERROR test "msg": "error message",\n' + - ' ERROR test "name": "TypeError",\n' + - ' ERROR test "stack": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile",\n' + - ' ERROR test "status": 500\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "err": {\n' + + ' ERROR test "msg": "error message",\n' + + ' ERROR test "name": "TypeError",\n' + + ' ERROR test "stack": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile",\n' + + ' ERROR test "status": 500\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.012Z {\n' + - ' ERROR test "a": {\n' + - ' ERROR test "b": {\n' + - ' ERROR test "c": 1\n' + - ' ERROR test },\n' + - ' ERROR test "e": "[Circular]"\n' + - ' ERROR test },\n' + - ' ERROR test "d": {\n' + - ' ERROR test "a": {\n' + - ' ERROR test "b": {\n' + - ' ERROR test "c": 1\n' + - ' ERROR test },\n' + - ' ERROR test "e": "[Circular]"\n' + - ' ERROR test },\n' + - ' ERROR test "d": "[Circular]"\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "a": {\n' + + ' ERROR test "b": {\n' + + ' ERROR test "c": 1\n' + + ' ERROR test },\n' + + ' ERROR test "e": "[Circular]"\n' + + ' ERROR test },\n' + + ' ERROR test "d": {\n' + + ' ERROR test "a": {\n' + + ' ERROR test "b": {\n' + + ' ERROR test "c": 1\n' + + ' ERROR test },\n' + + ' ERROR test "e": "[Circular]"\n' + + ' ERROR test },\n' + + ' ERROR test "d": "[Circular]"\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.013Z null +1ms', ' ERROR test 1970-01-01T00:00:00.014Z undefined +1ms', ' ERROR test 1970-01-01T00:00:00.015Z %d +1ms', @@ -68,78 +68,78 @@ export default { ' ERROR test 1970-01-01T00:00:00.017Z hello world +1ms', ' ERROR test 1970-01-01T00:00:00.018Z digit 42.7 +1ms', ' ERROR test 1970-01-01T00:00:00.019Z json {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test },\n' + - ' ERROR test "msg": "the message"\n' + - ' ERROR test } +1ms', + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test },\n' + + ' ERROR test "msg": "the message"\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.020Z obj {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test },\n' + - ' ERROR test "msg": "the message"\n' + - ' ERROR test } +1ms', + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test },\n' + + ' ERROR test "msg": "the message"\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.021Z obj [\n' + - ' ERROR test 1,\n' + - ' ERROR test 2,\n' + - ' ERROR test 3\n' + - ' ERROR test ] +1ms', + ' ERROR test 1,\n' + + ' ERROR test 2,\n' + + ' ERROR test 3\n' + + ' ERROR test ] +1ms', ' ERROR test 1970-01-01T00:00:00.022Z error {\n' + - ' ERROR test "status": 500\n' + - ' ERROR test } +1ms', + ' ERROR test "status": 500\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.023Z mixed % string 1.1 2.2 3.33 {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test },\n' + - ' ERROR test "msg": "the message"\n' + - ' ERROR test } {\n' + - ' ERROR test "status": 500\n' + - ' ERROR test } +1ms', + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test },\n' + + ' ERROR test "msg": "the message"\n' + + ' ERROR test } {\n' + + ' ERROR test "status": 500\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.024Z error message %s %% %d string 1.1 {\n' + - ' ERROR test "err": {\n' + - ' ERROR test "msg": "error message",\n' + - ' ERROR test "name": "TypeError",\n' + - ' ERROR test "stack": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile",\n' + - ' ERROR test "status": 500\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "err": {\n' + + ' ERROR test "msg": "error message",\n' + + ' ERROR test "name": "TypeError",\n' + + ' ERROR test "stack": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile",\n' + + ' ERROR test "status": 500\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.025Z the message {\n' + - ' ERROR test "err": {\n' + - ' ERROR test "msg": "error message",\n' + - ' ERROR test "name": "TypeError",\n' + - ' ERROR test "stack": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile",\n' + - ' ERROR test "status": 500\n' + - ' ERROR test },\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "err": {\n' + + ' ERROR test "msg": "error message",\n' + + ' ERROR test "name": "TypeError",\n' + + ' ERROR test "stack": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile",\n' + + ' ERROR test "status": 500\n' + + ' ERROR test },\n' + + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.026Z the message {\n' + - ' ERROR test "object": {\n' + - ' ERROR test "test": 1\n' + - ' ERROR test },\n' + - ' ERROR test "err": {\n' + - ' ERROR test "msg": "error message",\n' + - ' ERROR test "name": "TypeError",\n' + - ' ERROR test "stack": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile",\n' + - ' ERROR test "status": 500\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "object": {\n' + + ' ERROR test "test": 1\n' + + ' ERROR test },\n' + + ' ERROR test "err": {\n' + + ' ERROR test "msg": "error message",\n' + + ' ERROR test "name": "TypeError",\n' + + ' ERROR test "stack": "TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile",\n' + + ' ERROR test "status": 500\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.027Z {\n' + - ' ERROR test "7123000": 7123000,\n' + - ' ERROR test "_abcdEF$01": "abcdef",\n' + - ' ERROR test "0.1234": 0.1234,\n' + - ' ERROR test "s p-a c e": "space",\n' + - ' ERROR test "\\"\'``\\"": "\\"\'``\\"",\n' + - ' ERROR test "\\"": "\\"",\n' + - ' ERROR test "\'": "\'"\n' + - ' ERROR test } +1ms', + ' ERROR test "7123000": 7123000,\n' + + ' ERROR test "_abcdEF$01": "abcdef",\n' + + ' ERROR test "0.1234": 0.1234,\n' + + ' ERROR test "s p-a c e": "space",\n' + + ' ERROR test "\\"\'``\\"": "\\"\'``\\"",\n' + + ' ERROR test "\\"": "\\"",\n' + + ' ERROR test "\'": "\'"\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.028Z {\n' + - ' ERROR test "req": {\n' + - ' ERROR test "url": "/test",\n' + - ' ERROR test "ip": "10.10.10.10"\n' + - ' ERROR test }\n' + - ' ERROR test } +1ms', + ' ERROR test "req": {\n' + + ' ERROR test "url": "/test",\n' + + ' ERROR test "ip": "10.10.10.10"\n' + + ' ERROR test }\n' + + ' ERROR test } +1ms', ' ERROR test 1970-01-01T00:00:00.029Z with level +1ms' ], json: [ diff --git a/test/fixtures/testcases.js b/test/fixtures/testcases.js index a191f64..69dda7e 100644 --- a/test/fixtures/testcases.js +++ b/test/fixtures/testcases.js @@ -1,11 +1,16 @@ export const obj = { object: { test: 1 }, msg: 'the message' } -export const objEnsure = { name: { test: 1 }, msg: 'with level', level: 'NONESENSE' } +export const objEnsure = { + name: { test: 1 }, + msg: 'with level', + level: 'NONESENSE' +} export const arr = [1, 2, 3] export const err = new TypeError('error message') -err.stack = 'TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile' // shortened stack +err.stack = + 'TypeError: error message at Object. (./test/node.test.js:9:13) at Module._compile' // shortened stack err.status = 500 export const circular = { a: { b: { c: 1 } } } @@ -19,11 +24,11 @@ export const quotes = { 's p-a c e': 'space', '"\'``"': '"\'``"', '"': '"', - '\'': '\'' + "'": "'" } class Custom { - constructor (url) { + constructor(url) { Object.assign(this, { url, ip: '10.10.10.10', @@ -32,7 +37,7 @@ class Custom { }) } - toJSON () { + toJSON() { const { url, ip } = this return { url, ip } } @@ -64,7 +69,10 @@ export const testcases = [ { name: 'obj %o', args: ['obj %o', obj] }, { name: 'obj %O', args: ['obj %O', arr] }, { name: 'error %O', args: ['error %O', err] }, - { name: 'mixed %', args: ['mixed %% %s %d %d %d %j %O', 'string', 1.1, 2.2, 3.33, obj, err] }, + { + name: 'mixed %', + args: ['mixed %% %s %d %d %d %j %O', 'string', 1.1, 2.2, 3.33, obj, err] + }, { name: 'error %s %d', args: [err, '%s %% %d', 'string', 1.1] }, { name: 'error obj %s %d', args: [err, obj, '%s %% %d', 'string', 1.1] }, { name: '%s %d obj err', args: ['%s %% %d', 'string', 1.1, obj, err] }, diff --git a/test/helpers/describeBool.js b/test/helpers/describeBool.js index 5e0a807..8680967 100644 --- a/test/helpers/describeBool.js +++ b/test/helpers/describeBool.js @@ -4,10 +4,10 @@ const noop = () => {} -export const describeBool = (trueish) => trueish ? describe : describe.skip -describeBool.only = (trueish) => trueish ? describe.only : noop -describeBool.skip = (trueish) => describe.skip +export const describeBool = (trueish) => (trueish ? describe : describe.skip) +describeBool.only = (trueish) => (trueish ? describe.only : noop) +describeBool.skip = (_trueish) => describe.skip -export const itBool = (trueish) => trueish ? it : it.skip -itBool.only = (trueish) => trueish ? it.only : noop -itBool.skip = (trueish) => it.skip +export const itBool = (trueish) => (trueish ? it : it.skip) +itBool.only = (trueish) => (trueish ? it.only : noop) +itBool.skip = (_trueish) => it.skip diff --git a/test/helpers/karma-test-middleware.cjs b/test/helpers/karma-test-middleware.cjs index 477013e..562ce08 100644 --- a/test/helpers/karma-test-middleware.cjs +++ b/test/helpers/karma-test-middleware.cjs @@ -1,7 +1,7 @@ const { browserLogs } = require('../..') const loggerMw = browserLogs() -function factory () { +function factory() { return function (req, res, next) { if (/^\/logger/.test(req.url)) { req.ip = req.ip || req.connection.remoteAddress diff --git a/test/helpers/ua.js b/test/helpers/ua.js index b93dc85..7c23acf 100644 --- a/test/helpers/ua.js +++ b/test/helpers/ua.js @@ -1,9 +1,7 @@ export const ua = (() => { if (typeof globalThis.navigator !== 'undefined') { const ua = navigator.userAgent - return /firefox/i.test(ua) - ? 'firefox' - : 'chrome' + return /firefox/i.test(ua) ? 'firefox' : 'chrome' } })() diff --git a/test/httpLog.test.js b/test/httpLog.test.js index ad89247..f939296 100644 --- a/test/httpLog.test.js +++ b/test/httpLog.test.js @@ -19,7 +19,7 @@ describe('#httpLogs', function () { httpLogs()(req, res, () => {}) res.end() } - return request(app, '/').then(res => { + return request(app, '/').then((res) => { assert.equal(res.statusCode, 200) }) }) @@ -30,7 +30,7 @@ describe('#httpLogs', function () { res.statusCode = 400 res.end() } - return request(app, '/400').then(res => { + return request(app, '/400').then((res) => { assert.equal(res.statusCode, 400) }) }) @@ -41,7 +41,7 @@ describe('#httpLogs', function () { res.statusCode = 500 res.end() } - return request(app, '/500').then(res => { + return request(app, '/500').then((res) => { assert.equal(res.statusCode, 500) }) }) @@ -52,7 +52,7 @@ describe('#httpLogs', function () { res.writeHead(200) res.write(Array(10000).fill('...').join('')) } - request(app, '/abort').then(res => { + request(app, '/abort').then((res) => { res.on('data', () => { res.destroy() done() @@ -61,7 +61,8 @@ describe('#httpLogs', function () { }) it('log with custom req.id', function (done) { - const customGenerateRequestId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 6) + const customGenerateRequestId = () => + Date.now().toString(36) + Math.random().toString(36).slice(2, 6) const mw = httpLogs('my-module:http', { customGenerateRequestId }) const app = (req, res) => { mw(req, res, () => {}) @@ -73,19 +74,22 @@ describe('#httpLogs', function () { }) }) -function request (app, path) { +function request(app, path) { return new Promise((resolve) => { const server = http.createServer(app).listen(() => { const { port } = server.address() - const req = http.request({ - method: 'GET', - hostname: 'localhost', - port, - path - }, (res) => { - resolve(res) - server.close() - }) + const req = http.request( + { + method: 'GET', + hostname: 'localhost', + port, + path + }, + (res) => { + resolve(res) + server.close() + } + ) req.end() }) }) diff --git a/test/node.test.js b/test/node.test.js index dce236e..493bbf4 100644 --- a/test/node.test.js +++ b/test/node.test.js @@ -26,6 +26,7 @@ describe('Log node', function () { after(reset) it('should get default options', function () { + // eslint-disable-next-line no-unused-vars const { stream, serializers, toJson, ...res } = Log.options() assert.deepStrictEqual(res, { level: 'INFO', @@ -44,7 +45,13 @@ describe('Log node', function () { }) it('should set options', function () { - Log.options({ level: 'error', json: true, colors: false, namespaces: 'foo*,bar' }) + Log.options({ + level: 'error', + json: true, + colors: false, + namespaces: 'foo*,bar' + }) + // eslint-disable-next-line no-unused-vars const { stream, serializers, toJson, ...res } = Log.options() assert.deepStrictEqual(res, { level: 'error', @@ -63,7 +70,12 @@ describe('Log node', function () { }) it('should save options', function () { - Log.options({ level: 'ERROR', json: true, colors: false, namespaces: 'foo*,bar' }) + Log.options({ + level: 'ERROR', + json: true, + colors: false, + namespaces: 'foo*,bar' + }) Log.save() const res = Object.keys(process.env) .filter((env) => /^DEBUG/.test(env)) @@ -97,25 +109,44 @@ describe('Log node', function () { clock.restore() }) it('should log no time', function () { - const log = new Log('test', { timestamp: false, colors: false, namespaces: '*' }) + const log = new Log('test', { + timestamp: false, + colors: false, + namespaces: '*' + }) const res = log.log('a log line') assert.strictEqual(res, ' LOG test a log line +0ms') }) it('should log in iso time', function () { - const log = new Log('test', { timestamp: 'iso', colors: false, namespaces: '*' }) + const log = new Log('test', { + timestamp: 'iso', + colors: false, + namespaces: '*' + }) const res = log.log('a log line') - assert.strictEqual(res, ' LOG test 1970-01-01T00:01:26.000Z a log line +0ms') + assert.strictEqual( + res, + ' LOG test 1970-01-01T00:01:26.000Z a log line +0ms' + ) }) it('should log in epoch time', function () { - const log = new Log('test', { timestamp: 'epoch', colors: false, namespaces: '*' }) + const log = new Log('test', { + timestamp: 'epoch', + colors: false, + namespaces: '*' + }) const res = log.log('a log line') assert.strictEqual(res, ' LOG test 86000 a log line +0ms') }) it('should log in unix time', function () { - const log = new Log('test', { timestamp: 'unix', colors: false, namespaces: '*' }) + const log = new Log('test', { + timestamp: 'unix', + colors: false, + namespaces: '*' + }) const res = log.log('a log line') assert.strictEqual(res, ' LOG test 86 a log line +0ms') }) @@ -126,13 +157,13 @@ describe('Log node', function () { const tests = [ [undefined, { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - ['TRACE', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1, trace: 1 }], - ['DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - ['INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], - ['WARN', { fatal: 1, error: 1, warn: 1 }], - ['ERROR', { fatal: 1, error: 1 }], - ['FATAL', { fatal: 1 }], - ['OFF', {}] + ['TRACE', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1, trace: 1 }], + ['DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], + ['INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], + ['WARN', { fatal: 1, error: 1, warn: 1 }], + ['ERROR', { fatal: 1, error: 1 }], + ['FATAL', { fatal: 1 }], + ['OFF', {}] ] tests.forEach(([level, expects]) => { it('shall display logs for level ' + level, function () { @@ -165,17 +196,22 @@ describe('Log node', function () { const tests = [ [undefined, {}], - ['TRACE', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1, trace: 1 }], - ['DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - ['INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], - ['WARN', { fatal: 1, error: 1, warn: 1 }], - ['ERROR', { fatal: 1, error: 1 }], - ['FATAL', { fatal: 1 }], - ['OFF', {}] + ['TRACE', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1, trace: 1 }], + ['DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], + ['INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], + ['WARN', { fatal: 1, error: 1, warn: 1 }], + ['ERROR', { fatal: 1, error: 1 }], + ['FATAL', { fatal: 1 }], + ['OFF', {}] ] tests.forEach(([level, expects]) => { it('shall display logs for level ' + level, function () { - Log.options({ level, namespaces: undefined, json: false, colors: true }) + Log.options({ + level, + namespaces: undefined, + json: false, + colors: true + }) const log = new Log('test:' + (level || 'undefined').toLowerCase()) const res = { trace: log.trace('test') ? 1 : undefined, @@ -211,7 +247,12 @@ describe('Log node', function () { tests.forEach(([level, exp]) => { it('shall write levels as numbers for ' + level, function () { - const log = new Log('test', { levelNumbers: true, level: 'trace', json: true, colors: false }) + const log = new Log('test', { + levelNumbers: true, + level: 'trace', + json: true, + colors: false + }) const res = log[level]('test') assert.strictEqual(res, exp) }) @@ -224,22 +265,34 @@ describe('Log node', function () { const tests = [ // level, nsLevel, expects - [undefined, undefined, { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - [undefined, 'TRACE', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1, trace: 1 }], - [undefined, 'DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - [undefined, 'INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], - [undefined, 'WARN', { fatal: 1, error: 1, warn: 1 }], - [undefined, 'ERROR', { fatal: 1, error: 1 }], - [undefined, 'FATAL', { fatal: 1 }], - [undefined, 'OFF', {}], - ['ERROR', undefined, { fatal: 1, error: 1 }], - ['ERROR', 'TRACE', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1, trace: 1 }], - ['ERROR', 'DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - ['ERROR', 'INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], - ['ERROR', 'WARN', { fatal: 1, error: 1, warn: 1 }], - ['ERROR', 'ERROR', { fatal: 1, error: 1 }], - ['FATAL', 'FATAL', { fatal: 1 }], - ['ERROR', 'OFF', {}] + [ + undefined, + undefined, + { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 } + ], + [ + undefined, + 'TRACE', + { fatal: 1, error: 1, warn: 1, info: 1, debug: 1, trace: 1 } + ], + [undefined, 'DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], + [undefined, 'INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], + [undefined, 'WARN', { fatal: 1, error: 1, warn: 1 }], + [undefined, 'ERROR', { fatal: 1, error: 1 }], + [undefined, 'FATAL', { fatal: 1 }], + [undefined, 'OFF', {}], + ['ERROR', undefined, { fatal: 1, error: 1 }], + [ + 'ERROR', + 'TRACE', + { fatal: 1, error: 1, warn: 1, info: 1, debug: 1, trace: 1 } + ], + ['ERROR', 'DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], + ['ERROR', 'INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], + ['ERROR', 'WARN', { fatal: 1, error: 1, warn: 1 }], + ['ERROR', 'ERROR', { fatal: 1, error: 1 }], + ['FATAL', 'FATAL', { fatal: 1 }], + ['ERROR', 'OFF', {}] ] tests.forEach(([level, nsLevel, expects]) => { it(`shall display logs for level ${level} using namespaced-level ${nsLevel}`, function () { @@ -276,13 +329,83 @@ describe('Log node', function () { after(reset) const tests = [ - ['TRACE', { fatal: true, error: true, warn: true, info: true, debug: true, trace: true }], - ['DEBUG', { fatal: true, error: true, warn: true, info: true, debug: true, trace: false }], - ['INFO', { fatal: true, error: true, warn: true, info: true, debug: false, trace: false }], - ['WARN', { fatal: true, error: true, warn: true, info: false, debug: false, trace: false }], - ['ERROR', { fatal: true, error: true, warn: false, info: false, debug: false, trace: false }], - ['FATAL', { fatal: true, error: false, warn: false, info: false, debug: false, trace: false }], - ['OFF', { fatal: false, error: false, warn: false, info: false, debug: false, trace: false }] + [ + 'TRACE', + { + fatal: true, + error: true, + warn: true, + info: true, + debug: true, + trace: true + } + ], + [ + 'DEBUG', + { + fatal: true, + error: true, + warn: true, + info: true, + debug: true, + trace: false + } + ], + [ + 'INFO', + { + fatal: true, + error: true, + warn: true, + info: true, + debug: false, + trace: false + } + ], + [ + 'WARN', + { + fatal: true, + error: true, + warn: true, + info: false, + debug: false, + trace: false + } + ], + [ + 'ERROR', + { + fatal: true, + error: true, + warn: false, + info: false, + debug: false, + trace: false + } + ], + [ + 'FATAL', + { + fatal: true, + error: false, + warn: false, + info: false, + debug: false, + trace: false + } + ], + [ + 'OFF', + { + fatal: false, + error: false, + warn: false, + info: false, + debug: false, + trace: false + } + ] ] tests.forEach(([level, exp]) => { it('shall check if enabled for level ' + level, function () { @@ -312,7 +435,12 @@ describe('Log node', function () { before(() => { clock = sinon.useFakeTimers() - Log.options({ level: 'error', json: false, colors: false, namespaces: 'test*' }) + Log.options({ + level: 'error', + json: false, + colors: false, + namespaces: 'test*' + }) log = new Log('test', { timestamp: 'iso' }) }) @@ -342,14 +470,25 @@ describe('Log node', function () { const log = new Log('test:multiple', { level: 'DEBUG' }) const msg = '1 test\n2 test\n3 test' const res = log.error(msg) - assert.strictEqual(res, ' ERROR test:multiple 1 test\n ERROR test:multiple 2 test\n ERROR test:multiple 3 test +0ms') + assert.strictEqual( + res, + ' ERROR test:multiple 1 test\n ERROR test:multiple 2 test\n ERROR test:multiple 3 test +0ms' + ) }) it('should not log over multiple lines', function () { - const log = new Log('test:multiple', { json: false, splitLine: false, level: 'DEBUG', time: false }) + const log = new Log('test:multiple', { + json: false, + splitLine: false, + level: 'DEBUG', + time: false + }) const msg = '1 test\n2 test\n3 test' const res = log.error(msg) - assert.strictEqual(res, ' ERROR test:multiple 1 test\\n2 test\\n3 test +0ms') + assert.strictEqual( + res, + ' ERROR test:multiple 1 test\\n2 test\\n3 test +0ms' + ) }) }) @@ -359,7 +498,13 @@ describe('Log node', function () { before(() => { clock = sinon.useFakeTimers() - Log.options({ level: 'error', namespaces: 'test*', json: true, colors: true, serverinfo: false }) + Log.options({ + level: 'error', + namespaces: 'test*', + json: true, + colors: true, + serverinfo: false + }) log = new Log('test', { timestamp: 'epoch' }) }) @@ -367,7 +512,7 @@ describe('Log node', function () { clock.restore() }) - testcases.forEach(({ name, args }, idx) => { + testcases.forEach(({ name, args }, _idx) => { it(name, function () { const res = log.error(...args) clock.tick(1) @@ -385,7 +530,13 @@ describe('Log node', function () { before(() => { clock = sinon.useFakeTimers() - Log.options({ level: 'error', namespaces: 'test*', json: true, colors: false, serverinfo: false }) + Log.options({ + level: 'error', + namespaces: 'test*', + json: true, + colors: false, + serverinfo: false + }) log = new Log('test', { timestamp: 'epoch' }) }) @@ -407,13 +558,23 @@ describe('Log node', function () { it('should NOT remove object only formatters', function () { const log = new Log('*') const res = log.error('%j ', { a: { b: 'c' } }) - assert.strictEqual(res, '{"level":"ERROR","name":"*","msg":"{\\"a\\":{\\"b\\":\\"c\\"}} ","diff":0}') + assert.strictEqual( + res, + '{"level":"ERROR","name":"*","msg":"{\\"a\\":{\\"b\\":\\"c\\"}} ","diff":0}' + ) }) it('should log serverinfo and pid', function () { - const log = new Log('*', { level: undefined, serverinfo: true, json: true }) + const log = new Log('*', { + level: undefined, + serverinfo: true, + json: true + }) const res = log.error('test') - assert(res.indexOf('"hostname":"' + os.hostname()) !== -1, 'missing hostname') + assert( + res.indexOf('"hostname":"' + os.hostname()) !== -1, + 'missing hostname' + ) assert(res.indexOf('"pid":' + process.pid) !== -1, 'missing pid') }) @@ -424,18 +585,27 @@ describe('Log node', function () { err.stack = err.stack.substring(0, 20) const log = new Log('all') const res = log.log(err) - assert.strictEqual(res, '{"level":"LOG","name":"all","msg":"Baam","diff":0,"err":{"msg":"Baam","name":"Error","stack":"TEST_NAME: Baam\\n ","level":"TEST_LEVEL"}}') + assert.strictEqual( + res, + '{"level":"LOG","name":"all","msg":"Baam","diff":0,"err":{"msg":"Baam","name":"Error","stack":"TEST_NAME: Baam\\n ","level":"TEST_LEVEL"}}' + ) }) it('should stringify large string', function () { const largeString = new Array(150).fill('1').join('') const res = log.error({ largeString }) - assert.strictEqual(res, '{"level":"ERROR","time":30,"name":"test","diff":1,"largeString":"111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"}') + assert.strictEqual( + res, + '{"level":"ERROR","time":30,"name":"test","diff":1,"largeString":"111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"}' + ) }) it('should remove infinite number and function', function () { const res = log.error({ number: Infinity, fn: () => {} }) - assert.strictEqual(res, '{"level":"ERROR","time":30,"name":"test","diff":0}') + assert.strictEqual( + res, + '{"level":"ERROR","time":30,"name":"test","diff":0}' + ) }) }) }) @@ -446,13 +616,13 @@ describe('Log node', function () { describe('namespace *', function () { const tests = [ [undefined, { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - ['TRACE', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1, trace: 1 }], - ['DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], - ['INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], - ['WARN', { fatal: 1, error: 1, warn: 1 }], - ['ERROR', { fatal: 1, error: 1 }], - ['FATAL', { fatal: 1 }], - ['OFF', {}] + ['TRACE', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1, trace: 1 }], + ['DEBUG', { fatal: 1, error: 1, warn: 1, info: 1, debug: 1 }], + ['INFO', { fatal: 1, error: 1, warn: 1, info: 1 }], + ['WARN', { fatal: 1, error: 1, warn: 1 }], + ['ERROR', { fatal: 1, error: 1 }], + ['FATAL', { fatal: 1 }], + ['OFF', {}] ] tests.forEach(([level, expects]) => { it('shall always log for level ' + level, function () { @@ -496,7 +666,10 @@ describe('Log node', function () { const err = new Error('baamm') err.stack = 'Error: baam\n at Context.' const res = log.error({ msg: 'boom', err }) - assert.strictEqual(res, '{"level":"ERROR","name":"serialize","msg":"boom","diff":0,"err":{"msg":"baamm","name":"Error","stack":"Error: baam\\n at Context."}}') + assert.strictEqual( + res, + '{"level":"ERROR","name":"serialize","msg":"boom","diff":0,"err":{"msg":"baamm","name":"Error","stack":"Error: baam\\n at Context."}}' + ) }) it('shall log with custom serializer', function () { @@ -505,11 +678,18 @@ describe('Log node', function () { const { foo } = val return foo } - const log = new Log('serialize', { json: true, colors: false, serializers: { my } }) + const log = new Log('serialize', { + json: true, + colors: false, + serializers: { my } + }) const err = new Error('baamm') err.stack = 'Error: baam\n at Context.' const res = log.error({ msg: 'boom', my: { foo: 'bar', level: 42 }, err }) - assert.strictEqual(res, '{"level":"ERROR","name":"serialize","msg":"boom","diff":0,"my":"bar","err":{"msg":"baamm","name":"Error","stack":"Error: baam\\n at Context."}}') + assert.strictEqual( + res, + '{"level":"ERROR","name":"serialize","msg":"boom","diff":0,"my":"bar","err":{"msg":"baamm","name":"Error","stack":"Error: baam\\n at Context."}}' + ) }) }) @@ -526,7 +706,12 @@ describe('Log node', function () { describe('wrap console', function () { let unwrap before(function () { - Log.options({ level: 'trace', namespaces: 'test', json: true, colors: true }) + Log.options({ + level: 'trace', + namespaces: 'test', + json: true, + colors: true + }) unwrap = Log.wrapConsole('test') }) after(function () { diff --git a/test/quick-format.test.js b/test/quick-format.test.js index 7719ba8..d59fb6b 100644 --- a/test/quick-format.test.js +++ b/test/quick-format.test.js @@ -57,7 +57,10 @@ describe('quick-format', function () { assert.strictEqual(format('%s', [undefined]), 'undefined') assert.strictEqual(format('%s', ['foo']), 'foo') assert.strictEqual(format('%s', ['"quoted"']), '"quoted"') - assert.strictEqual(format('%j', [{ s: '"quoted"' }]), '{"s":"\\"quoted\\""}') + assert.strictEqual( + format('%j', [{ s: '"quoted"' }]), + '{"s":"\\"quoted\\""}' + ) assert.strictEqual(format('%s:%s', []), '%s:%s') assert.strictEqual(format('%s:%s', [undefined]), 'undefined:%s') assert.strictEqual(format('%s:%s', ['foo']), 'foo:%s') @@ -74,13 +77,23 @@ describe('quick-format', function () { assert.strictEqual(format('foo %o', [{ foo: 'foo' }]), 'foo {"foo":"foo"}') assert.strictEqual(format('foo %O', [{ foo: 'foo' }]), 'foo {"foo":"foo"}') assert.strictEqual(format('foo %j', [{ foo: 'foo' }]), 'foo {"foo":"foo"}') - assert.strictEqual(format('foo %j %j', [{ foo: 'foo' }]), 'foo {"foo":"foo"} %j') - assert.strictEqual(format('foo %j', ['foo']), 'foo \'foo\'') // TODO: isn't this wrong? - assert.strictEqual(format('foo %j', [function foo () {}]), 'foo foo()') + assert.strictEqual( + format('foo %j %j', [{ foo: 'foo' }]), + 'foo {"foo":"foo"} %j' + ) + assert.strictEqual(format('foo %j', ['foo']), "foo 'foo'") // TODO: isn't this wrong? + assert.strictEqual(format('foo %j', [function foo() {}]), 'foo foo()') assert.strictEqual(format('foo %j', [function () {}]), 'foo ()') - assert.strictEqual(format('foo %j', [{ foo: 'foo' }, 'not-printed']), 'foo {"foo":"foo"} not-printed') assert.strictEqual( - format('foo %j', [{ foo: 'foo' }], { stringify () { return 'REPLACED' } }), + format('foo %j', [{ foo: 'foo' }, 'not-printed']), + 'foo {"foo":"foo"} not-printed' + ) + assert.strictEqual( + format('foo %j', [{ foo: 'foo' }], { + stringify() { + return 'REPLACED' + } + }), 'foo REPLACED' ) const circularObject = {} @@ -95,24 +108,38 @@ describe('quick-format', function () { assert.strictEqual(format('%%%s%%%%', ['hi']), '%hi%%') }) it('functions', function () { - function test () {} + function test() {} assert.strictEqual(format(test, []), 'test()') - assert.strictEqual(format('%s', [test]), 'function test () {}') + assert.strictEqual(format('%s', [test]), 'function test() {}') assert.strictEqual(format('%s', ['hi', test]), 'hi test()') - assert.strictEqual(format(() => {}, []), '()') + assert.strictEqual( + format(() => {}, []), + '()' + ) assert.strictEqual(format('%s', [() => {}]), '() => {}') assert.strictEqual(format('%s', ['hi', () => {}]), 'hi ()') }) it('object assignment', function () { const obj = {} - assert.strictEqual(format('%s%%%s', ['foo', 'bar', { hello: 'object' }, { test: 1 }], {}, obj), 'foo%bar') + assert.strictEqual( + format( + '%s%%%s', + ['foo', 'bar', { hello: 'object' }, { test: 1 }], + {}, + obj + ), + 'foo%bar' + ) assert.deepStrictEqual(obj, { hello: 'object', test: 1 }) }) it('no formatter', function () { const obj = {} - assert.strictEqual(format({ hello: 'object' }, ['foo', 'bar', { test: 1 }], {}, obj), ' foo bar') + assert.strictEqual( + format({ hello: 'object' }, ['foo', 'bar', { test: 1 }], {}, obj), + ' foo bar' + ) assert.deepStrictEqual(obj, { hello: 'object', test: 1 }) }) it('error', function () { diff --git a/test/utils.test.js b/test/utils.test.js index 4ef4b16..413025e 100644 --- a/test/utils.test.js +++ b/test/utils.test.js @@ -68,13 +68,25 @@ describe('#utils', function () { describe('numbered levels', function () { it('shall convert to numbered levels', function () { - const res = LEVELS.TRACE.concat(LOG, '##').map(l => toNumLevel(l)) + const res = LEVELS.TRACE.concat(LOG, '##').map((l) => toNumLevel(l)) assert.deepStrictEqual(res, [60, 50, 40, 30, 20, 10, 30, 20]) }) it('shall convert back to readable levels', function () { - const res = [101, 60, 51, 50, 40, 30, 20, 10, 0].map(l => fromNumLevel(l)) - assert.deepStrictEqual(res, ['FATAL', 'FATAL', 'FATAL', 'ERROR', 'WARN', 'INFO', 'DEBUG', 'TRACE', 'TRACE']) + const res = [101, 60, 51, 50, 40, 30, 20, 10, 0].map((l) => + fromNumLevel(l) + ) + assert.deepStrictEqual(res, [ + 'FATAL', + 'FATAL', + 'FATAL', + 'ERROR', + 'WARN', + 'INFO', + 'DEBUG', + 'TRACE', + 'TRACE' + ]) }) }) }) diff --git a/types/Format.d.ts b/types/Format.d.ts index 06b77a1..3a2733c 100644 --- a/types/Format.d.ts +++ b/types/Format.d.ts @@ -6,7 +6,7 @@ export class Format { /** * @param {FormatOption} [opts] */ - constructor(opts?: FormatOption | undefined); + constructor(opts?: FormatOption); opts: { spaces: number | undefined; }; diff --git a/types/LogBase.d.ts b/types/LogBase.d.ts index bfa9ad4..b832981 100644 --- a/types/LogBase.d.ts +++ b/types/LogBase.d.ts @@ -32,19 +32,19 @@ export class LogBase { _timeF: any; _time: any; /** always logs */ - log: (...args: any[]) => void; + log: (..._args: any[]) => void; /** log with level FATAL */ - fatal: (...args: any[]) => void; + fatal: (..._args: any[]) => void; /** log with level ERROR */ - error: (...args: any[]) => void; + error: (..._args: any[]) => void; /** log with level WARN */ - warn: (...args: any[]) => void; + warn: (..._args: any[]) => void; /** log with level INFO */ - info: (...args: any[]) => void; + info: (..._args: any[]) => void; /** log with level DEBUG */ - debug: (...args: any[]) => void; + debug: (..._args: any[]) => void; /** log with level TRACE */ - trace: (...args: any[]) => void; + trace: (..._args: any[]) => void; /** @type {number|undefined} */ pid: number | undefined; /** @type {string|undefined} */ @@ -52,7 +52,7 @@ export class LogBase { /** * @param {string} [namespaces] */ - enable(namespaces?: string | undefined): void; + enable(namespaces?: string): void; get enabled(): any; diff(): number; _prev: number | undefined; @@ -65,7 +65,7 @@ export class LogBase { /** * @protected */ - protected _log(nlevel: any, fmt: any, args: any): void; + protected _log(_nlevel: any, _fmt: any, _args: any): void; } export type Timestamp = "epoch" | "unix" | "iso"; export type Level = import("./utils.js").Level; diff --git a/types/Sonic.d.ts b/types/Sonic.d.ts index 6316769..32b0e6b 100644 --- a/types/Sonic.d.ts +++ b/types/Sonic.d.ts @@ -34,7 +34,7 @@ export class SonicStreams extends Map { * @param {SonicOptions} [opts] * @returns {Sonic} */ - use(stream: NodeJS.WriteStream, opts?: SonicOptions | undefined): Sonic; + use(stream: NodeJS.WriteStream, opts?: SonicOptions): Sonic; } export const sonicStreams: SonicStreams; export type SonicOptions = { diff --git a/types/browser.d.ts b/types/browser.d.ts index 22caf61..44ee2e6 100644 --- a/types/browser.d.ts +++ b/types/browser.d.ts @@ -7,7 +7,7 @@ export class Log extends LogBase { * @param {LogOptionsBrowser} [opts] changed options * @return {object} global options */ - static options(opts?: LogOptionsBrowser | undefined): object; + static options(opts?: LogOptionsBrowser): object; /** * save options in `localStorage` */ @@ -29,9 +29,9 @@ export class Log extends LogBase { * @param {LogOptionWrapConsole} [opts] * @return {function} unwrap function */ - static wrapConsole(name?: string | undefined, opts?: (import("./Format.js").FormatOption & import("./LogBase.js").ExtLogBaseOptions & ExtLogOptionsBrowser & { + static wrapConsole(name?: string, opts?: import("./Format.js").FormatOption & import("./LogBase.js").ExtLogBaseOptions & ExtLogOptionsBrowser & { level4log?: import("./utils.js").Level | undefined; - }) | undefined): Function; + }): Function; /** * @param {string} name namespace of Logger * @param {LogOptionsBrowser} opts @@ -86,17 +86,17 @@ export class Log extends LogBase { * render arguments to console.log * @public * @param {any[]} args console.log arguments - * @param {Level} level level of log line (might be used for custom Logger which uses different streams per level) + * @param {Level} [_level] level of log line (might be used for custom Logger which uses different streams per level) * @return {any[]} */ - public render(args: any[], level: Level): any[]; + public render(args: any[], _level?: Level): any[]; /** * send log to server * @param {Level|object} level log level * @param {string} [fmt] formatter * @param {any[]} [args] log arguments */ - send(level: Level | object, fmt?: string | undefined, args?: any[] | undefined): void; + send(level: Level | object, fmt?: string, args?: any[]): void; /** * format log arguments * @protected @@ -105,7 +105,7 @@ export class Log extends LogBase { /** * format arguments for console.log * @private - * @param {object} param0 + * @param {object} options * @return {Array} args for console.log */ private _format; @@ -114,7 +114,7 @@ export class Log extends LogBase { * @param {string} str * @param {Function} [cb] */ - _sendLog(str: string, cb?: Function | undefined): void; + _sendLog(str: string, cb?: Function): void; /** * Add colors, style to string * @private diff --git a/types/browserLogs.d.ts b/types/browserLogs.d.ts index 729a2f4..5ee163c 100644 --- a/types/browserLogs.d.ts +++ b/types/browserLogs.d.ts @@ -16,7 +16,7 @@ * @param {MwLogOption} [options] * @return {function} connect middleware */ -export function browserLogs(options?: MwLogOption | undefined): Function; +export function browserLogs(options?: MwLogOption): Function; /** * - [maxSize=100] max number of different name loggers * - [logAll=false] log everything even strings diff --git a/types/httpLogs.d.ts b/types/httpLogs.d.ts index 6a3f68a..ed74eb5 100644 --- a/types/httpLogs.d.ts +++ b/types/httpLogs.d.ts @@ -18,7 +18,7 @@ * @param {LogOptionsHttpLog} [opts] * @returns {(req: IncomingMessageWithId, res: ServerResponse, next: Function) => void} connect middleware */ -export function httpLogs(namespace?: string | undefined, opts?: LogOptionsHttpLog | undefined): (req: IncomingMessageWithId, res: ServerResponse, next: Function) => void; +export function httpLogs(namespace?: string, opts?: LogOptionsHttpLog): (req: IncomingMessageWithId, res: ServerResponse, next: Function) => void; export type IncomingMessage = import("node:http").IncomingMessage; export type ServerResponse = import("node:http").ServerResponse; export type LogOptions = import("./node.js").LogOptions; diff --git a/types/logger.d.ts b/types/logger.d.ts index 8b5c9c1..a2bf18c 100644 --- a/types/logger.d.ts +++ b/types/logger.d.ts @@ -5,5 +5,5 @@ * @param {string} namespace * @param {LogOptions} [opts] */ -export function logger(namespace: string, opts?: import("./index.js").LogOptions | undefined): any; +export function logger(namespace: string, opts?: LogOptions): any; export type LogOptions = import("./index.js").LogOptions; diff --git a/types/node.d.ts b/types/node.d.ts index cac72e6..2eaa1d8 100644 --- a/types/node.d.ts +++ b/types/node.d.ts @@ -3,7 +3,7 @@ * @param {number} [spaces] * @returns {string} */ -export function stringify(any: any, spaces?: number | undefined): string; +export function stringify(any: any, spaces?: number): string; export class Log extends LogBase { /** * Apply (and get) global options @@ -26,21 +26,21 @@ export class Log extends LogBase { * @param {LogOptionWrapConsole} [opts] options * @return {function} unwrap function */ - static wrapConsole(name?: string | undefined, opts?: LogOptionWrapConsole | undefined): Function; + static wrapConsole(name?: string, opts?: LogOptionWrapConsole): Function; /** * log exit events like 'unhandledRejection', 'uncaughtException' * and then let the process die * @param {string} [name='exit'] * @param {LogOptionHandleExitEvents} [opts] options */ - static handleExitEvents(name?: string | undefined, opts?: LogOptionHandleExitEvents): void; + static handleExitEvents(name?: string, opts?: LogOptionHandleExitEvents): void; static wrapDebug(): () => void; /** * creates a new logger * @param {String} name - namespace of Logger * @param {LogOptions} [opts] - see Log.options */ - constructor(name: string, opts?: LogOptions | undefined); + constructor(name: string, opts?: LogOptions); color: any; levColors: {}; opts: { @@ -112,10 +112,10 @@ export class Log extends LogBase { * render string to output stream * @public * @param {String} str string to render - * @param {String} level level of log line (might be used for custom Logger which uses different streams per level) + * @param {String} [_level] level of log line (might be used for custom Logger which uses different streams per level) * @return {String} */ - public render(str: string, level: string): string; + public render(str: string, _level?: string): string; flush(): void; /** * format object to json @@ -178,7 +178,7 @@ import { LogBase } from './LogBase.js'; * @param {number} [spaces] * @returns {string} */ -declare function toJson(obj: object, serializers: object, spaces?: number | undefined): string; +declare function toJson(obj: object, serializers: object, spaces?: number): string; import { Sonic } from './Sonic.js'; declare const isDevEnv: boolean; import { errSerializer } from './serializers/index.js';