| 1 |
const { log } = require('proc-log') |
| 2 |
const fs = require('node:fs') |
| 3 |
const { dirname } = require('node:path') |
| 4 |
const os = require('node:os') |
| 5 |
const { inspect, format } = require('node:util') |
| 6 |
|
| 7 |
const { bin: options } = require('./options.js') |
| 8 |
|
| 9 |
// add a meta method to proc-log for passing optional |
| 10 |
// metadata through to log handlers |
| 11 |
const META = Symbol('meta') |
| 12 |
const parseArgs = (...args) => { |
| 13 |
const { [META]: isMeta } = args[args.length - 1] || {} |
| 14 |
return isMeta |
| 15 |
? [args[args.length - 1], ...args.slice(0, args.length - 1)] |
| 16 |
: [{}, ...args] |
| 17 |
} |
| 18 |
log.meta = (meta = {}) => ({ [META]: true, ...meta }) |
| 19 |
|
| 20 |
const levels = new Map([ |
| 21 |
'silly', |
| 22 |
'verbose', |
| 23 |
'info', |
| 24 |
'http', |
| 25 |
'notice', |
| 26 |
'warn', |
| 27 |
'error', |
| 28 |
'silent', |
| 29 |
].map((level, index) => [level, index])) |
| 30 |
|
| 31 |
const addLogListener = (write, { eol = os.EOL, loglevel = 'silly', colors = false } = {}) => { |
| 32 |
const levelIndex = levels.get(loglevel) |
| 33 |
|
| 34 |
const magenta = m => colors ? `\x1B[35m${m}\x1B[39m` : m |
| 35 |
const dim = m => colors ? `\x1B[2m${m}\x1B[22m` : m |
| 36 |
const red = m => colors ? `\x1B[31m${m}\x1B[39m` : m |
| 37 |
|
| 38 |
const formatter = (level, ...args) => { |
| 39 |
const depth = level === 'error' && args[0] && args[0].code === 'ERESOLVE' ? Infinity : 10 |
| 40 |
|
| 41 |
if (level === 'info' && args[0] === 'timeEnd') { |
| 42 |
args[1] = dim(args[1]) |
| 43 |
} else if (level === 'error' && args[0] === 'timeError') { |
| 44 |
args[1] = red(args[1]) |
| 45 |
} |
| 46 |
|
| 47 |
const messages = args.map(a => typeof a === 'string' ? a : inspect(a, { depth, colors })) |
| 48 |
const pref = `${process.pid} ${magenta(level)} ` |
| 49 |
|
| 50 |
return pref + format(...messages).trim().split('\n').join(`${eol}${pref}`) + eol |
| 51 |
} |
| 52 |
|
| 53 |
process.on('log', (...args) => { |
| 54 |
const [meta, level, ...logArgs] = parseArgs(...args) |
| 55 |
|
| 56 |
if (levelIndex <= levels.get(level) || meta.force) { |
| 57 |
write(formatter(level, ...logArgs)) |
| 58 |
} |
| 59 |
}) |
| 60 |
} |
| 61 |
|
| 62 |
if (options.loglevel !== 'silent') { |
| 63 |
addLogListener((v) => process.stderr.write(v), { |
| 64 |
eol: '\n', |
| 65 |
colors: options.colors, |
| 66 |
loglevel: options.loglevel, |
| 67 |
}) |
| 68 |
} |
| 69 |
|
| 70 |
if (options.logfile) { |
| 71 |
log.silly('logfile', options.logfile) |
| 72 |
fs.mkdirSync(dirname(options.logfile), { recursive: true }) |
| 73 |
const fd = fs.openSync(options.logfile, 'a') |
| 74 |
addLogListener((str) => fs.writeSync(fd, str)) |
| 75 |
} |
| 76 |
|
| 77 |
module.exports = log |