domino-server/src/common/LoggingService.ts
2024-07-05 01:19:43 +02:00

102 lines
2.3 KiB
TypeScript

import pino, { BaseLogger } from 'pino';
import path from 'path';
export class LoggingService {
static instance: LoggingService;
logsPath: string = path.join(process.cwd(), 'app', 'server', 'logs');
logger!: BaseLogger;
level: string = process.env.LOG_LEVEL || 'info';
/*
* ogger.fatal('fatal');
logger.error('error');
logger.warn('warn');
logger.info('info');
logger.debug('debug');
logger.trace('trace');
*/
constructor() {
if ((!LoggingService.instance)) {
LoggingService.instance = this;
this.logger = pino({
level: this.level,
timestamp: pino.stdTimeFunctions.isoTime,
}, this.transports);
}
return LoggingService.instance;
}
get commonRorationOptions() : any {
return {
interval: '1d',
maxFiles: 10,
path: this.logsPath,
size: '10M',
maxSize: '100M',
};
}
get transports() {
return pino.transport({
targets: [
// {
// target: 'pino-rotating-file-stream',
// level: this.level,
// options: {
// filename: 'app.log',
// ...this.commonRorationOptions
// },
// },
{
target: 'pino-pretty',
level: this.level,
options: {
sync: true,
colorized: true,
}
},
]
});
}
debug(message: string, data?: any) {
this.logger.debug(this._getMessageWidthObject(message, data));
}
info(message: string, data?: any) {
this.logger.info(this._getMessageWidthObject(message, data));
}
warn(message: string, data?: any) {
this.logger.warn(this._getMessageWidthObject(message, data));
}
error(error: any, message?: string) {
this.logger.error(error, message);
}
fatal(message: string, data?: any) {
this.logger.fatal(this._getMessageWidthObject(message, data));
}
trace(message: string, data?: any) {
this.logger.trace(this._getMessageWidthObject(message, data));
}
object(message: any) {
this.logger.info(JSON.stringify(message, null, 2));
}
_getMessageWidthObject(message: string, data?: any) {
if (!data) {
return message;
}
return `${message}\n${this._getStringObject(data)}`;
}
_getStringObject(data: any) {
return JSON.stringify(data, null, 2);
}
}