2024-05-14 08:48:49 -04:00
|
|
|
import { ConsoleLogger, Injectable, Scope } from '@nestjs/common';
|
|
|
|
|
import { isLogLevelEnabled } from '@nestjs/common/services/utils/is-log-level-enabled.util';
|
2024-04-15 19:39:06 -04:00
|
|
|
import { ClsService } from 'nestjs-cls';
|
|
|
|
|
import { LogLevel } from 'src/entities/system-config.entity';
|
|
|
|
|
import { ILoggerRepository } from 'src/interfaces/logger.interface';
|
2024-05-14 08:48:49 -04:00
|
|
|
|
|
|
|
|
const LOG_LEVELS = [LogLevel.VERBOSE, LogLevel.DEBUG, LogLevel.LOG, LogLevel.WARN, LogLevel.ERROR, LogLevel.FATAL];
|
2024-04-15 19:39:06 -04:00
|
|
|
|
2024-04-17 03:00:31 +05:30
|
|
|
@Injectable({ scope: Scope.TRANSIENT })
|
2024-05-14 08:48:49 -04:00
|
|
|
export class LoggerRepository extends ConsoleLogger implements ILoggerRepository {
|
|
|
|
|
private static logLevels: LogLevel[] = [LogLevel.LOG, LogLevel.WARN, LogLevel.ERROR, LogLevel.FATAL];
|
|
|
|
|
|
2024-04-15 19:39:06 -04:00
|
|
|
constructor(private cls: ClsService) {
|
|
|
|
|
super(LoggerRepository.name);
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-14 08:48:49 -04:00
|
|
|
isLevelEnabled(level: LogLevel) {
|
|
|
|
|
return isLogLevelEnabled(level, LoggerRepository.logLevels);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
setLogLevel(level: LogLevel): void {
|
|
|
|
|
LoggerRepository.logLevels = LOG_LEVELS.slice(LOG_LEVELS.indexOf(level));
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-15 19:39:06 -04:00
|
|
|
protected formatContext(context: string): string {
|
|
|
|
|
let formattedContext = super.formatContext(context);
|
|
|
|
|
|
|
|
|
|
const correlationId = this.cls?.getId();
|
|
|
|
|
if (correlationId && this.isLevelEnabled(LogLevel.VERBOSE)) {
|
|
|
|
|
formattedContext += `[${correlationId}] `;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return formattedContext;
|
|
|
|
|
}
|
|
|
|
|
}
|