在Node.js里实时查看日志,其实比想象中要简单。通常来说,你有几种常用手段可以选,每种都挺实用,关键看你的场景和习惯。
最直接的方法:console.log / console.error
如果只是开发调试阶段,最简单粗暴的方式就是直接使用console.log()和console.error()。当你运行应用时,这些输出会实时显示在控制台上,不需要任何额外配置。比如:
console.log('This is an info log');
console.error('This is an error log');
不过,这种方法在生产环境里就不太够用了——日志没法持久化,也很难按级别筛选。
专业级方案:引入日志库(winston / morgan)
如果你想对日志做更精细的控制——比如分级、格式化、输出到文件和轮转——那么值得试试第三方库。社区里比较成熟的是winston和morgan(后者更偏向HTTP请求日志)。以winston为例,先安装:
npm install winston
然后配置起来很直观:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/combined.log' }),
],
});
logger.info('This is an info log');
logger.error('This is an error log');
这样一来,日志会同时输出到控制台和文件,按级别分开存储,方便后续排查。而且winston还支持自定义格式、多传输端,甚至能跟第三方日志服务对接,扩展性很好。
终极大法:tail -f 实时追踪文件
如果你已经将日志写到了文件里,比如上面winston生成的combined.log,那么最经典、最轻量的实时查看方式就是tail -f命令。在终端里跑:
tail -f logs/combined.log
这会显示文件末尾几行,并且在新内容写入时自动刷新。很多运维老手就靠这一招,配合日志轮转,就能搞定大部分线上问题的追踪。
说到底,选择哪种方法取决于你的需求:临时调试用console,生产环境强烈建议用winston这类库,再加个tail -f作为辅助。没有银弹,但组合使用效果最佳。
