improve nest logger

This commit is contained in:
syuilo
2022-12-10 15:45:30 +09:00
parent b4b742ca89
commit 2067180328
4 changed files with 68 additions and 13 deletions

View File

@@ -5,7 +5,7 @@ import { format as dateFormat } from 'date-fns';
import { bindThis } from '@/decorators.js';
import { envOption } from './env.js';
type Domain = {
type Context = {
name: string;
color?: string;
};
@@ -13,14 +13,14 @@ type Domain = {
type Level = 'error' | 'success' | 'warning' | 'debug' | 'info';
export default class Logger {
private domain: Domain;
private context: Context;
private parentLogger: Logger | null = null;
private store: boolean;
private syslogClient: any | null = null;
constructor(domain: string, color?: string, store = true, syslogClient = null) {
this.domain = {
name: domain,
constructor(context: string, color?: string, store = true, syslogClient = null) {
this.context = {
name: context,
color: color,
};
this.store = store;
@@ -28,20 +28,20 @@ export default class Logger {
}
@bindThis
public createSubLogger(domain: string, color?: string, store = true): Logger {
const logger = new Logger(domain, color, store);
public createSubLogger(context: string, color?: string, store = true): Logger {
const logger = new Logger(context, color, store);
logger.parentLogger = this;
return logger;
}
@bindThis
private log(level: Level, message: string, data?: Record<string, any> | null, important = false, subDomains: Domain[] = [], store = true): void {
private log(level: Level, message: string, data?: Record<string, any> | null, important = false, subContexts: Context[] = [], store = true): void {
if (envOption.quiet) return;
if (!this.store) store = false;
if (level === 'debug') store = false;
if (this.parentLogger) {
this.parentLogger.log(level, message, data, important, [this.domain].concat(subDomains), store);
this.parentLogger.log(level, message, data, important, [this.context].concat(subContexts), store);
return;
}
@@ -54,7 +54,7 @@ export default class Logger {
level === 'debug' ? chalk.gray('VERB') :
level === 'info' ? chalk.blue('INFO') :
null;
const domains = [this.domain].concat(subDomains).map(d => d.color ? chalk.rgb(...convertColor.keyword.rgb(d.color))(d.name) : chalk.white(d.name));
const contexts = [this.context].concat(subContexts).map(d => d.color ? chalk.rgb(...convertColor.keyword.rgb(d.color))(d.name) : chalk.white(d.name));
const m =
level === 'error' ? chalk.red(message) :
level === 'warning' ? chalk.yellow(message) :
@@ -63,7 +63,7 @@ export default class Logger {
level === 'info' ? message :
null;
let log = `${l} ${worker}\t[${domains.join(' ')}]\t${m}`;
let log = `${l} ${worker}\t[${contexts.join(' ')}]\t${m}`;
if (envOption.withLogTime) log = chalk.gray(time) + ' ' + log;
console.log(important ? chalk.bold(log) : log);