TypeScript 应用日志记录简介
\n\n日志记录是记录程序运行期间发生事件的过程。对于 TypeScript 应用,尤其是在 Node.js 环境中运行的应用,配置良好的日志记录不仅是一种良好习惯,更是调试、监控和分析错误的关键工具。
\n\n许多初学者开发者仅限于使用 console.log()。然而,在生产环境中,这种方法效率低下:它无法灵活管理重要性级别、过滤消息或将其保存到文件中。在本文中,我们将探讨如何从零开始在 TypeScript 中构建专业的日志记录系统。
为什么不应该在生产环境中使用 console.log?
\n\n来看一个典型示例:
\n\n// 糟糕的做法——直接使用 console.log\nfunction processOrder(orderId: string): void {\n console.log(`Processing order ${orderId}`);\n try {\n // 业务逻辑\n } catch (error) {\n console.error(`Error processing order: ${error}`);\n }\n}\n\n\n这种方法的问题:
\n- \n
- 缺少日志级别:无法将调试消息与关键错误区分开。 \n
- 无格式化:难以阅读大量数据。 \n
- 无法重定向:所有消息仅输出到 stdout/stderr。 \n
- 性能问题:同步写入控制台可能会拖慢应用。 \n
TypeScript 日志记录的最佳实践
\n\n1. 选择日志记录库
\n\n对于 TypeScript,建议使用两个流行的库之一:
\n- \n
- Winston — 功能强大且灵活的日志记录器,支持传输(文件、控制台、数据库)。 \n
- Pino — 超高速日志记录器,非常适合高负载应用。 \n
安装 Winston:
\nnpm install winston\nnpm install @types/winston --save-dev\n\n\n2. 创建可配置的日志记录器
\n\n创建一个 logger.ts 模块:
import winston from 'winston';\n\nconst logger = winston.createLogger({\n level: process.env.LOG_LEVEL || 'info',\n format: winston.format.combine(\n winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),\n winston.format.errors({ stack: true }),\n winston.format.json()\n ),\n transports: [\n new winston.transports.Console({\n format: winston.format.combine(\n winston.format.colorize(),\n winston.format.simple()\n )\n }),\n new winston.transports.File({ \n filename: 'logs/error.log', \n level: 'error' \n }),\n new winston.transports.File({ \n filename: 'logs/combined.log' \n })\n ]\n});\n\nexport default logger;\n\n\n现在可以在任何模块中使用日志记录器:
\nimport logger from './logger';\n\nfunction getUser(id: string) {\n logger.info(`Fetching user with ID: ${id}`);\n try {\n // 获取用户的逻辑\n logger.debug('User data retrieved successfully');\n } catch (error) {\n logger.error('Failed to fetch user', { userId: id, error });\n }\n}\n\n\n3. 使用日志级别
\n\n标准级别(从最不重要到最重要):
\n- \n
- debug — 详细的调试信息(仅用于开发)。 \n
- info — 标准信息性消息。 \n
- warn — 潜在问题的警告。 \n
- error — 需要关注的错误。 \n
通过环境变量配置日志级别:
\n// 在 .env 文件中\nLOG_LEVEL=debug # 用于开发\nLOG_LEVEL=warn # 用于生产\n\n\n4. 结构化日志记录
\n\n传递附加