using-logging

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Working with Logging

日志记录实践

Use structured logging with Pino throughout your application. Covers log levels, context, and workflow-safe logging patterns.
在整个应用中使用Pino进行结构化日志记录。涵盖日志级别、上下文以及工作流安全的日志记录模式。

Implement Working with Logging

实现日志记录实践

Use structured logging with Pino throughout your application. Covers log levels, context, and workflow-safe logging patterns.
See:

在整个应用中使用Pino进行结构化日志记录。涵盖日志级别、上下文以及工作流安全的日志记录模式。
参考:

Basic Logging

基础日志记录

Import the logger and use it throughout your application:
typescript
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" });
导入日志工具并在整个应用中使用:
typescript
import { logger } from "@/lib/logging/logger";

// 信息级别:用于常规操作
logger.info("Server started", { port: 3000 });

// 警告级别:用于可恢复的问题
logger.warn("Rate limit reached", { endpoint: "/api/chat" });

// 错误级别:搭配Error对象使用
logger.error(err, "Failed to process request");

// 调试级别:用于开发阶段排查问题
logger.debug("Cache miss", { key: "user:123" });

Structured Logging

结构化日志记录

Always include context as the first argument for structured logs:
typescript
// 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");
始终将上下文作为结构化日志的第一个参数:
typescript
// 先传上下文对象,再传消息
logger.info({ userId: "123", action: "login" }, "User logged in");

// 处理错误时,先传错误对象
logger.error({ err, userId: "123", endpoint: "/api/chat" }, "Request failed");

Log Levels

日志级别

Use appropriate levels for different scenarios:
| Level | When to Use | |
trace
| Detailed debugging (rarely used) | |
debug
| Development troubleshooting | |
info
| Normal operations, business events | |
warn
| Recoverable issues, deprecation warnings | |
error
| Failures that need attention | |
fatal
| Critical failures, app cannot continue |
针对不同场景使用合适的日志级别:
| 级别 | 使用场景 | |
trace
| 详细调试信息(极少使用) | |
debug
| 开发阶段排查问题 | |
info
| 常规操作、业务事件 | |
warn
| 可恢复问题、弃用警告 | |
error
| 需要关注的失败情况 | |
fatal
| 严重故障,应用无法继续运行 |

Configuring Log Level

配置日志级别

Set the
LOG_LEVEL
environment variable:
env
undefined
设置
LOG_LEVEL
环境变量:
env
undefined

Show all logs including debug

显示所有日志,包括调试信息

LOG_LEVEL="debug"
LOG_LEVEL="debug"

Production: only warnings and errors

生产环境:仅显示警告和错误

LOG_LEVEL="warn"

Default is `info` if not set. Valid values: `trace`, `debug`, `info`, `warn`, `error`, `fatal`.
LOG_LEVEL="warn"

若未设置,默认级别为`info`。有效值包括:`trace`, `debug`, `info`, `warn`, `error`, `fatal`。

Logging in API Routes

API路由中的日志记录

typescript
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 });
  }
}
typescript
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 });
  }
}

Logging in Workflows

工作流中的日志记录

Workflow functions run in a restricted environment. Use the logger step wrapper:
typescript
// 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);
  }
}
Then use it in workflows:
typescript
import { log } from "./steps/logger";

export async function chatWorkflow({ chatId }) {
  "use workflow";

  await log("info", "Workflow started", { chatId });
}

工作流函数运行在受限环境中,请使用日志步骤包装器:
typescript
// 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);
  }
}
然后在工作流中使用:
typescript
import { log } from "./steps/logger";

export async function chatWorkflow({ chatId }) {
  "use workflow";

  await log("info", "Workflow started", { chatId });
}

References

参考资料