关于 logging-best-practices
logging-best-practices 是面向软件开发者的安全结构化日志指南,涵盖日志级别、请求上下文、个人信息脱敏,以及多种语言和可观测性系统的实现参考。
主要功能
- 01日志级别使用指引
- 02结构化 JSON 日志
- 03请求上下文与关联 ID
- 04个人信息脱敏
- 05多语言实现参考
适用场景
- 01为应用添加结构化日志
- 02关联跨服务事件
- 03从日志中隐藏敏感数据
- 04制定生产环境日志规范
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ secondsky/ claude-skills --skill logging-best-practices安装后在 Claude Code 中输入/logging-best-practices确认已加载。
附带文件references/advanced-logging.md
详细介绍
日志记录最佳实践
实施安全、结构化的日志记录,并使用适当的级别和上下文。
日志级别
| 级别 | 用途 | 生产环境 |
|---|---|---|
| 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' })
]
});
// Usage
logger.info('User logged in', { userId: '123', ip: '192.168.1.1' });
logger.error('Payment failed', { 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] = '[REDACTED]';
}
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 Stack 集成
- AWS CloudWatch 配置
- OpenTelemetry 跟踪
绝对不要
- 记录密码或令牌
- 在生产环境中使用 console.log
- 在紧密循环中记录日志
- 在客户端错误中包含堆栈跟踪
评论
支持 Markdown