关于 using-logging
Fullstack Recipes 中关于使用 Pino 实现结构化日志的技能,涵盖日志级别、上下文信息、环境配置,以及适用于工作流代码的日志模式。
主要功能
- 01Pino 结构化日志
- 02日志级别及适用场景
- 03配置 LOG_LEVEL
- 04为请求添加上下文信息
- 05适用于工作流的日志模式
适用场景
- 01为 API 路由添加上下文日志
- 02为运行事件选择日志级别
- 03按环境调整日志详细程度
- 04在工作流函数中记录日志
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ andrelandgraf/ fullstackrecipes --skill using-logging安装后在 Claude Code 中输入/using-logging确认已加载。
详细介绍
使用日志记录
在整个应用中使用 Pino 进行结构化日志记录。涵盖日志级别、上下文和适用于工作流的日志记录模式。
实现日志记录
在整个应用中使用 Pino 进行结构化日志记录。涵盖日志级别、上下文和适用于工作流的日志记录模式。
参见:
- 资源:Fullstack Recipes 中的
using-logging - URL:https://fullstackrecipes.com/recipes/using-logging
基本日志记录
导入 logger 并在整个应用中使用:
import { logger } from "@/lib/logging/logger";
// Info level for normal operations
logger.info("Server started", { port: 3000 });
// Warn level for recoverable issues
logger.warn("Rate limit reached", { endpoint: "/api/chat" });
// Error level with Error objects
logger.error(err, "Failed to process request");
// Debug level for development troubleshooting
logger.debug("Cache miss", { key: "user:123" });
结构化日志记录
结构化日志始终将上下文作为第一个参数:
// Context object first, message second
logger.info({ userId: "123", action: "login" }, "User logged in");
// For errors, pass the error first
logger.error({ err, userId: "123", endpoint: "/api/chat" }, "Request failed");
日志级别
针对不同场景使用适当的级别:
| 级别 | 使用场景 |
| trace | 详细调试(很少使用) |
| debug | 开发过程中的问题排查 |
| info | 常规操作、业务事件 |
| warn | 可恢复的问题、弃用警告 |
| error | 需要关注的故障 |
| fatal | 严重故障,应用无法继续运行 |
配置日志级别
设置 LOG_LEVEL 环境变量:
# Show all logs including debug
LOG_LEVEL="debug"
# Production: only warnings and errors
LOG_LEVEL="warn"
如果未设置,默认值为 info。有效值:trace、debug、info、warn、error、fatal。
在 API 路由中记录日志
import { logger } from "@/lib/logging/logger";
export async function POST(request: Request) {
const start = Date.now();
try {
const result = await processRequest(request);
logger.info(
{ duration: Date.now() - start, status: 200 },
"Request completed",
);
return Response.json(result);
} catch (err) {
logger.error({ err, duration: Date.now() - start }, "Request failed");
return Response.json({ error: "Internal error" }, { status: 500 });
}
}
在工作流中记录日志
工作流函数在受限环境中运行。使用 logger 步骤包装器:
// src/workflows/chat/steps/logger.ts
import { logger } from "@/lib/logging/logger";
export async function log(
level: "info" | "warn" | "error" | "debug",
message: string,
data?: Record<string, unknown>,
): Promise<void> {
"use step";
if (data) {
logger[level](data, message);
} else {
logger[level](message);
}
}
然后在工作流中使用:
import { log } from "./steps/logger";
export async function chatWorkflow({ chatId }) {
"use workflow";
await log("info", "Workflow started", { chatId });
}
参考资料
评论
支持 Markdown