refactor(server): no color env (#13166)

This commit is contained in:
Jason Rasmussen
2024-10-03 16:58:15 -04:00
committed by GitHub
parent 0eb77147ef
commit e2bf6808ca
7 changed files with 117 additions and 34 deletions

View File

@@ -1,18 +1,34 @@
import { ConsoleLogger, Injectable, Scope } from '@nestjs/common';
import { ConsoleLogger, Inject, Injectable, Scope } from '@nestjs/common';
import { isLogLevelEnabled } from '@nestjs/common/services/utils/is-log-level-enabled.util';
import { ClsService } from 'nestjs-cls';
import { LogLevel } from 'src/enum';
import { IConfigRepository } from 'src/interfaces/config.interface';
import { ILoggerRepository } from 'src/interfaces/logger.interface';
import { LogColor } from 'src/utils/logger';
const LOG_LEVELS = [LogLevel.VERBOSE, LogLevel.DEBUG, LogLevel.LOG, LogLevel.WARN, LogLevel.ERROR, LogLevel.FATAL];
enum LogColor {
RED = 31,
GREEN = 32,
YELLOW = 33,
BLUE = 34,
MAGENTA_BRIGHT = 95,
CYAN_BRIGHT = 96,
}
@Injectable({ scope: Scope.TRANSIENT })
export class LoggerRepository extends ConsoleLogger implements ILoggerRepository {
private static logLevels: LogLevel[] = [LogLevel.LOG, LogLevel.WARN, LogLevel.ERROR, LogLevel.FATAL];
private noColor: boolean;
constructor(private cls: ClsService) {
constructor(
private cls: ClsService,
@Inject(IConfigRepository) configRepository: IConfigRepository,
) {
super(LoggerRepository.name);
const { noColor } = configRepository.getEnv();
this.noColor = noColor;
}
private static appName?: string = undefined;
@@ -44,6 +60,19 @@ export class LoggerRepository extends ConsoleLogger implements ILoggerRepository
return '';
}
return LogColor.yellow(`[${prefix}]`) + ' ';
return this.colors.yellow(`[${prefix}]`) + ' ';
}
private colors = {
red: (text: string) => this.withColor(text, LogColor.RED),
green: (text: string) => this.withColor(text, LogColor.GREEN),
yellow: (text: string) => this.withColor(text, LogColor.YELLOW),
blue: (text: string) => this.withColor(text, LogColor.BLUE),
magentaBright: (text: string) => this.withColor(text, LogColor.MAGENTA_BRIGHT),
cyanBright: (text: string) => this.withColor(text, LogColor.CYAN_BRIGHT),
};
private withColor(text: string, color: LogColor) {
return this.noColor ? text : `\u001B[${color}m${text}\u001B[39m`;
}
}