// logger.js
|
const winston = require('winston');
|
|
/**
|
* 配置winston日志
|
*/
|
const DailyRotateFile = require('winston-daily-rotate-file');
|
const fs = require('fs');
|
const path = require('path');
|
|
const baseDir = (typeof process !== 'undefined' && process.pkg) ? path.dirname(process.execPath) : __dirname;
|
const logsDir = path.join(baseDir, 'logs');
|
if (!fs.existsSync(logsDir)) {
|
fs.mkdirSync(logsDir);
|
}
|
|
const logger = winston.createLogger({
|
level: process.env.LOG_LEVEL || 'info',
|
format: winston.format.combine(
|
winston.format.timestamp({
|
format: 'YYYY-MM-DD HH:mm:ss'
|
}),
|
winston.format.errors({ stack: true }),
|
winston.format.splat(),
|
winston.format.json()
|
),
|
defaultMeta: { service: 'dialysis-server' },
|
transports: [
|
new DailyRotateFile({
|
dirname: logsDir,
|
filename: 'error-%DATE%.log',
|
datePattern: 'YYYY-MM-DD',
|
level: 'error',
|
zippedArchive: true,
|
maxFiles: '10d',
|
}),
|
new DailyRotateFile({
|
dirname: logsDir,
|
filename: 'combined-%DATE%.log',
|
datePattern: 'YYYY-MM-DD',
|
zippedArchive: true,
|
maxFiles: '10d',
|
}),
|
]
|
});
|
|
// 如果不是生产环境,也输出到控制台
|
if (process.env.NODE_ENV !== 'production') {
|
logger.add(new winston.transports.Console({
|
format: winston.format.combine(
|
winston.format.colorize(),
|
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
|
winston.format.printf(({ level, message, timestamp, ...meta }) => {
|
try {
|
return `${level}: ${message} ${JSON.stringify(meta)}`;
|
} catch (_) {
|
return `${level}: ${message}`;
|
}
|
})
|
)
|
}));
|
}
|
|
// 提供按设备序列号的子 logger,便于按设备追踪
|
logger.forDevice = (deviceSerial, ip, clientId) => logger.child({ deviceSerial, ip, clientId });
|
|
module.exports = logger;
|