在Node.js应用中,通常通过第三方模块或自定义逻辑来完成日志的切分与存档。以下是一些常用的实现方式:
该模块是基于winston封装的日志切割组件,支持按天进行日志文件轮换。首先需要安装该模块:
npm install winston-daily-rotate-file
接着,在项目代码中引入并配置使用:
const winston = require('winston'); const DailyRotateFile = require('winston-daily-rotate-file'); const transport = new DailyRotateFile({ filename: 'application-%DATE%.log', datePattern: 'YYYY-MM-DD-HH', zippedArchive: true, maxSize: '20m', maxFiles: '14d' }); const logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ transport ] }); logger.info('Hello, world!');
以上配置将根据日期生成日志文件,单个文件最大容量为20MB,保留最近14天内的日志,并对历史文件进行压缩处理。
pino是一款高性能日志记录器,结合其他插件可轻松实现日志文件管理。先执行安装命令:
npm install pino pino-pretty pino-daily-rotate-file
随后在代码中进行如下初始化配置:
const pino = require('pino'); const pinoPretty = require('pino-pretty'); const pinoDailyRotateFile = require('pino-daily-rotate-file'); const logger = pino({ level: 'info' }, pinoDailyRotateFile({ period: '1d', dir: 'logs', prefix: 'application' })); logger.info('Hello, world!'); // 如需美化控制台输出格式,可配合使用 pino-pretty pinoPretty({ colorize: true }).pipe(process.stdout);
此示例将日志按天进行拆分,统一存放至logs目录下,文件名以application开头。
通过上述方案,可以灵活地实现Node.js项目的日志管理功能,具体参数可根据实际业务需求进行调整。
以上就是Node.js日志分割与归档方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号