traxxx-web/src/logger.js

54 lines
1.5 KiB
JavaScript
Executable File

import util from 'util';
import path from 'path';
import * as winston from 'winston';
import 'winston-daily-rotate-file';
import stackParser from 'error-stack-parser';
// import args from './args';
export default function initLogger(customLabel) {
const filepath = stackParser.parse(new Error())[1]?.fileName;
const contextLabel = customLabel || path.basename(filepath, '.js');
return winston.createLogger({
format: winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
winston.format((info) => (info instanceof Error
? { ...info, message: info.stack }
: { ...info, message: typeof info.message === 'string' ? info.message : util.inspect(info.message) }))(),
winston.format.colorize(),
winston.format.printf(({
level, timestamp, label, message,
}) => `${timestamp} ${level} [${label || contextLabel}] ${message}`),
),
transports: [
new winston.transports.Console({
level: 'silly',
timestamp: true,
}),
new winston.transports.DailyRotateFile({
datePattern: 'YYYY-MM-DD',
filename: path.join('log', '%DATE%.log'),
level: 'silly',
}),
],
});
}
export function initAccessLogger() {
return winston.createLogger({
level: 'access',
levels: {
access: 0,
},
format: winston.format.printf((data) => JSON.stringify({ ...data.message, timestamp: new Date() })),
transports: [
new winston.transports.DailyRotateFile({
datePattern: 'YYYY-MM-DD',
filename: path.join('log', 'access_%DATE%.log'),
level: 'access',
}),
],
});
}