名称: 日志记录最佳实践 描述: 结构化日志记录,具有适当的级别、上下文、PII处理、集中聚合。用于应用日志记录、日志管理集成、分布式追踪,或遇到日志膨胀、PII暴露、缺少上下文错误时。
日志记录最佳实践
实现安全、结构化的日志记录,具有适当的级别和上下文。
日志级别
| 级别 | 用于 | 生产环境 |
|---|---|---|
| DEBUG | 详细调试 | 关闭 |
| INFO | 正常操作 | 开启 |
| WARN | 潜在问题 | 开启 |
| ERROR | 可恢复错误 | 开启 |
| FATAL | 关键故障 | 开启 |
结构化日志记录 (Winston)
const winston = require('winston');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
defaultMeta: { service: 'api-service' },
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' })
]
});
// 用法
logger.info('用户登录', { userId: '123', ip: '192.168.1.1' });
logger.error('支付失败', { error: err.message, orderId: '456' });
请求上下文
const { AsyncLocalStorage } = require('async_hooks');
const storage = new AsyncLocalStorage();
app.use((req, res, next) => {
const context = {
requestId: req.headers['x-request-id'] || uuid(),
userId: req.user?.id
};
storage.run(context, next);
});
function log(level, message, meta = {}) {
const context = storage.getStore() || {};
logger.log(level, message, { ...context, ...meta });
}
PII 清理
const sensitiveFields = ['password', 'ssn', 'creditCard', 'token'];
function sanitize(obj) {
const sanitized = { ...obj };
for (const field of sensitiveFields) {
if (sanitized[field]) sanitized[field] = '[已屏蔽]';
}
if (sanitized.email) {
sanitized.email = sanitized.email.replace(/(.{2}).*@/, '$1***@');
}
return sanitized;
}
最佳实践
- 使用结构化JSON格式
- 在服务间包含关联ID
- 在日志记录前清理所有PII
- 使用异步日志记录以提高性能
- 实施日志轮转
- 在生产环境中切勿使用DEBUG级别日志
附加实现
参见 references/advanced-logging.md 获取:
- Python structlog 设置
- Go zap 高性能日志记录
- ELK 栈集成
- AWS CloudWatch 配置
- OpenTelemetry 追踪
切勿做
- 记录密码或令牌
- 在生产环境中使用 console.log
- 在紧密循环中记录日志
- 为客户端错误包含堆栈跟踪