80 lines
1.7 KiB
JavaScript
80 lines
1.7 KiB
JavaScript
/**
|
|
* 简单日志工具
|
|
* 支持日志级别和格式化输出
|
|
*/
|
|
|
|
const config = require('../config');
|
|
|
|
const LEVELS = {
|
|
debug: 0,
|
|
info: 1,
|
|
warn: 2,
|
|
error: 3
|
|
};
|
|
|
|
const COLORS = {
|
|
debug: '\x1b[36m', // cyan
|
|
info: '\x1b[32m', // green
|
|
warn: '\x1b[33m', // yellow
|
|
error: '\x1b[31m', // red
|
|
reset: '\x1b[0m'
|
|
};
|
|
|
|
const currentLevel = LEVELS[config.log.level] || LEVELS.info;
|
|
const colorize = config.log.colorize && process.stdout.isTTY;
|
|
|
|
function formatTime() {
|
|
const d = new Date();
|
|
return d.toISOString().replace('T', ' ').slice(0, 19);
|
|
}
|
|
|
|
function formatMessage(level, ...args) {
|
|
const timestamp = formatTime();
|
|
const prefix = `[${timestamp}] [${level.toUpperCase()}]`;
|
|
|
|
if (colorize) {
|
|
return `${COLORS[level]}${prefix}${COLORS.reset} ${args.join(' ')}`;
|
|
}
|
|
return `${prefix} ${args.join(' ')}`;
|
|
}
|
|
|
|
const logger = {
|
|
debug(...args) {
|
|
if (currentLevel <= LEVELS.debug) {
|
|
console.log(formatMessage('debug', ...args));
|
|
}
|
|
},
|
|
|
|
info(...args) {
|
|
if (currentLevel <= LEVELS.info) {
|
|
console.log(formatMessage('info', ...args));
|
|
}
|
|
},
|
|
|
|
warn(...args) {
|
|
if (currentLevel <= LEVELS.warn) {
|
|
console.warn(formatMessage('warn', ...args));
|
|
}
|
|
},
|
|
|
|
error(...args) {
|
|
if (currentLevel <= LEVELS.error) {
|
|
console.error(formatMessage('error', ...args));
|
|
}
|
|
},
|
|
|
|
// 请求日志中间件
|
|
requestLogger(req, res, next) {
|
|
const start = Date.now();
|
|
res.on('finish', () => {
|
|
const duration = Date.now() - start;
|
|
const status = res.statusCode;
|
|
const level = status >= 400 ? 'warn' : 'info';
|
|
logger[level](`${req.method} ${req.originalUrl || req.url} ${status} ${duration}ms`);
|
|
});
|
|
next();
|
|
}
|
|
};
|
|
|
|
module.exports = logger;
|