2024-01-30 14:19:45 +00:00
|
|
|
import * as log4js from 'log4js';
|
|
|
|
import moment from 'moment';
|
2024-03-14 13:50:57 +00:00
|
|
|
import { REQUEST } from '@nestjs/core';
|
|
|
|
import { Inject, Request } from '@nestjs/common';
|
2024-01-30 14:19:45 +00:00
|
|
|
const log4jsLogger = log4js.getLogger();
|
|
|
|
|
|
|
|
export class Logger {
|
2024-03-14 13:50:57 +00:00
|
|
|
private static inited = false;
|
|
|
|
|
|
|
|
constructor(@Inject(REQUEST) private req: Request) {}
|
2024-01-30 14:19:45 +00:00
|
|
|
|
2024-03-14 13:50:57 +00:00
|
|
|
static init(config: { filename: string }) {
|
2024-01-30 14:19:45 +00:00
|
|
|
if (this.inited) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
log4js.configure({
|
|
|
|
appenders: {
|
|
|
|
app: {
|
|
|
|
type: 'dateFile',
|
|
|
|
filename: config.filename || './logs/app.log',
|
|
|
|
pattern: 'yyyy-MM-dd',
|
|
|
|
alwaysIncludePattern: true,
|
|
|
|
numBackups: 7,
|
|
|
|
layout: {
|
|
|
|
type: 'pattern',
|
|
|
|
pattern: '%m',
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
categories: {
|
|
|
|
default: { appenders: ['app'], level: 'trace' },
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
_log(message, options: { dltag?: string; level: string }) {
|
|
|
|
const datetime = moment().format('YYYY-MM-DD HH:mm:ss.SSS');
|
|
|
|
const level = options.level;
|
|
|
|
const dltag = options.dltag ? `${options.dltag}||` : '';
|
2024-03-14 13:50:57 +00:00
|
|
|
const traceIdStr = this.req['traceId']
|
|
|
|
? `traceid=${this.req['traceId']}||`
|
|
|
|
: '';
|
2024-01-30 14:19:45 +00:00
|
|
|
return log4jsLogger[level](
|
2024-03-14 13:50:57 +00:00
|
|
|
`[${datetime}][${level.toUpperCase()}]${dltag}${traceIdStr}${message}`,
|
2024-01-30 14:19:45 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
info(message, options = { dltag: '' }) {
|
|
|
|
return this._log(message, { ...options, level: 'info' });
|
|
|
|
}
|
|
|
|
|
|
|
|
error(message, options = { dltag: '' }) {
|
|
|
|
return this._log(message, { ...options, level: 'error' });
|
|
|
|
}
|
|
|
|
}
|