From 570b727cf105d523949acd6059f29499c91dc25d Mon Sep 17 00:00:00 2001 From: Innei Date: Sun, 13 Feb 2022 22:23:24 +0800 Subject: [PATCH] refactor: logger and fix color --- ecosystem.config.js | 2 +- pm2.dev.config.js | 3 +- src/global/consola.global.ts | 132 ++++++++++++++++++----------------- src/global/index.global.ts | 13 ++-- 4 files changed, 77 insertions(+), 73 deletions(-) diff --git a/ecosystem.config.js b/ecosystem.config.js index cea4ced5..428863b9 100644 --- a/ecosystem.config.js +++ b/ecosystem.config.js @@ -8,7 +8,7 @@ module.exports = { watch: false, instances: 2, max_memory_restart: '230M', - + args: '--color', env: { NODE_ENV: 'production', }, diff --git a/pm2.dev.config.js b/pm2.dev.config.js index c6374d14..b037149b 100644 --- a/pm2.dev.config.js +++ b/pm2.dev.config.js @@ -10,10 +10,11 @@ module.exports = { max_memory_restart: '230M', env: { + DEBUG_COLORS: true, NODE_ENV: 'development', }, - args: '--allowed_origins=dev.* --cluster', + args: '--allowed_origins=dev.* --cluster --color', }, ], } diff --git a/src/global/consola.global.ts b/src/global/consola.global.ts index 36c511a8..0c040447 100644 --- a/src/global/consola.global.ts +++ b/src/global/consola.global.ts @@ -1,85 +1,89 @@ +/* eslint-disable prefer-rest-params */ import { CronExpression } from '@nestjs/schedule' -import consola_, { - ConsolaReporterArgs, - ConsolaReporterLogObject, - FancyReporter, - LogLevel, -} from 'consola' +import consola_, { FancyReporter, LogLevel } from 'consola' import { CronJob } from 'cron' -import { createWriteStream, WriteStream } from 'fs' +import { createWriteStream } from 'fs' import { resolve } from 'path' import { argv } from 'zx' import { LOG_DIR } from '~/constants/path.constant' import { redisSubPub } from '../utils/redis-subpub.util' -import { getShortDate } from '../utils/time.util' +import { getShortDate, getShortTime } from '../utils/time.util' import { isDev, isTest } from './env.global' export const getTodayLogFilePath = () => resolve(LOG_DIR, 'stdout_' + getShortDate(new Date()) + '.log') -class DateTimeReporter extends FancyReporter { - private fs: WriteStream - private job: CronJob - constructor() { - super() - this.fs = createWriteStream(getTodayLogFilePath(), { +class Reporter extends FancyReporter { + protected formatDate(date: Date): string { + return '' + } + + protected formatLogObj(): string { + return ( + chalk.gray(getShortTime(new Date())) + + ' ' + + super.formatLogObj.apply(this, arguments).replace(/^\n/, '') + ).trim() + } +} +export const consola = consola_.create({ + reporters: [new Reporter()], + level: isDev || argv.verbose ? LogLevel.Trace : LogLevel.Info, +}) +export function registerStdLogger() { + let logStream = createWriteStream(getTodayLogFilePath(), { + encoding: 'utf-8', + flags: 'a+', + }) + + logStream.write( + '\n========================================================\n', + ) + + const job = new CronJob(CronExpression.EVERY_DAY_AT_MIDNIGHT, () => { + logStream.destroy() + + logStream = createWriteStream(getTodayLogFilePath(), { encoding: 'utf-8', flags: 'a+', }) - - this.fs.write( + logStream.write( '\n========================================================\n', ) + }) + job.start() - this.job = new CronJob(CronExpression.EVERY_DAY_AT_MIDNIGHT, () => { - this.fs.close() + const stdout = process.stdout.write + const stderr = process.stderr.write - this.fs = createWriteStream(getTodayLogFilePath(), { - encoding: 'utf-8', - flags: 'a+', - }) - this.fs.write( - '\n========================================================\n', - ) - }) - this.job.start() - } - // consola right time formater - formatDate(date: Date) { - return date.toLocaleString(undefined, { - hour12: false, - timeStyle: 'medium', - dateStyle: 'short', - }) - } - - public log(logObj: ConsolaReporterLogObject, args: ConsolaReporterArgs) { - super.log(logObj, args) - - if (!isTest) { - ;(async () => { - const formatOutput = - `${chalk.gray(this.formatDate(new Date()))} ` + - // @ts-expect-error - super.formatLogObj(logObj, { width: args.columns || 0 }) + - '\n' - if (this.fs) { - this.fs.write(formatOutput) - } - redisSubPub.publish('log', formatOutput) - })() + function log(data: string) { + if (isTest) { + return } + logStream.write(data) + redisSubPub.publish('log', data) } + + process.stdout.write = function () { + log(arguments[0]) + + return stdout.apply(this, arguments) + } + + process.stderr.write = function () { + log(arguments[0]) + return stderr.apply(this, arguments) + } + + consola.wrapAll() + Object.defineProperty(process.stdout, 'write', { + value: process.stdout.write, + writable: false, + configurable: false, + }) + Object.defineProperty(process.stderr, 'write', { + value: process.stdout.write, + writable: false, + configurable: false, + }) } -const consola = consola_.create({ - reporters: [new DateTimeReporter()], - level: isDev || argv.verbose ? LogLevel.Trace : LogLevel.Info, -}) - -const console = global.console -const stdout = process.stdout -const stderr = process.stderr - -// HINT: must be called before any other log calls, export it in the end of your file -consola.wrapAll() -export { consola } diff --git a/src/global/index.global.ts b/src/global/index.global.ts index 826a2f73..5c7c4878 100644 --- a/src/global/index.global.ts +++ b/src/global/index.global.ts @@ -9,7 +9,7 @@ import { TEMP_DIR, USER_ASSET_DIR, } from '~/constants/path.constant' -import { consola } from './consola.global' +import { consola, registerStdLogger } from './consola.global' import './dayjs.global' import { isDev } from './env.global' @@ -29,20 +29,19 @@ function mkdirs() { function registerGlobal() { $.verbose = isDev - + Object.assign(globalThis, { + isDev: isDev, + consola, + }) console.debug = (...rest) => { if (isDev) { consola.log.call(console, ...rest) } } - - Object.assign(globalThis, { - isDev: isDev, - consola, - }) } export function register() { + registerStdLogger() mkdirs() registerGlobal() }