Logging: Add LogLevels to ConsoleLoggerService

Signed-off-by: Philip Molares <philip.molares@udo.edu>
This commit is contained in:
Philip Molares 2021-04-13 23:13:47 +02:00
parent a039b85ff4
commit 327206d60c

View file

@ -4,17 +4,24 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { Injectable, Optional, Scope } from '@nestjs/common';
import { Inject, Injectable, Optional, Scope } from '@nestjs/common';
import { isObject } from '@nestjs/common/utils/shared.utils';
import clc = require('cli-color');
import DateTimeFormatOptions = Intl.DateTimeFormatOptions;
import appConfiguration, { AppConfig } from '../config/app.config';
import { Loglevel } from '../config/loglevel.enum';
import { needToLog } from '../config/utils';
@Injectable({ scope: Scope.TRANSIENT })
export class ConsoleLoggerService {
private classContext: string;
private lastTimestamp: number;
constructor(@Optional() context?: string) {
constructor(
@Inject(appConfiguration.KEY)
private appConfig: AppConfig,
@Optional() context?: string,
) {
this.classContext = context;
}
@ -29,43 +36,51 @@ export class ConsoleLoggerService {
this.makeContextString(functionContext),
false,
);
this.printStackTrace(trace);
ConsoleLoggerService.printStackTrace(trace);
}
log(message: unknown, functionContext?: string): void {
this.printMessage(
message,
clc.green,
this.makeContextString(functionContext),
false,
);
if (needToLog(this.appConfig.loglevel, Loglevel.INFO)) {
this.printMessage(
message,
clc.green,
this.makeContextString(functionContext),
false,
);
}
}
warn(message: unknown, functionContext?: string): void {
this.printMessage(
message,
clc.yellow,
this.makeContextString(functionContext),
false,
);
if (needToLog(this.appConfig.loglevel, Loglevel.WARN)) {
this.printMessage(
message,
clc.yellow,
this.makeContextString(functionContext),
false,
);
}
}
debug(message: unknown, functionContext?: string): void {
this.printMessage(
message,
clc.magentaBright,
this.makeContextString(functionContext),
false,
);
if (needToLog(this.appConfig.loglevel, Loglevel.DEBUG)) {
this.printMessage(
message,
clc.magentaBright,
this.makeContextString(functionContext),
false,
);
}
}
verbose(message: unknown, functionContext?: string): void {
this.printMessage(
message,
clc.cyanBright,
this.makeContextString(functionContext),
false,
);
if (needToLog(this.appConfig.loglevel, Loglevel.TRACE)) {
this.printMessage(
message,
clc.cyanBright,
this.makeContextString(functionContext),
false,
);
}
}
private makeContextString(functionContext: string): string {
@ -117,7 +132,7 @@ export class ConsoleLoggerService {
return result;
}
private printStackTrace(trace: string): void {
private static printStackTrace(trace: string): void {
if (!trace) {
return;
}