encore-logging
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseEncore.ts structured logging
Encore.ts 结构化日志
Use for application events that need structured fields or trace integration. Preserve an application's established field names and event conventions when they are consistent with this guidance.
encore.dev/log对于需要结构化字段或 trace 集成的应用事件,请使用 。如果应用既有的字段名称和事件约定与本指南一致,请予以保留。
encore.dev/logDecide what to record
决定记录哪些内容
Add logs for information Encore cannot infer from infrastructure operations:
- Business state transitions
- Decisions and the inputs that determined them
- Retries, fallbacks, and degraded operation
- Failures at the boundary that decides whether to retry, recover, or abort
- External-system interactions that require domain context
- Security-relevant or administrative actions
Encore already traces API requests, database queries, service calls, cache operations, and Pub/Sub activity. Do not narrate that execution with logs such as , , or .
request startedquerying databaserequest completedUse metrics for aggregate counts and levels. Use traces for call flow and timing. Use logs for the context needed to investigate an individual event.
应记录 Encore 无法从基础设施操作中推断的信息:
- 业务状态转换
- 决策及作出这些决策的输入
- 重试、回退和降级运行
- 在决定应重试、恢复还是中止的边界处发生的故障
- 需要领域上下文的外部系统交互
- 安全相关或管理操作
Encore 已经追踪 API 请求、数据库查询、service 调用、缓存操作和 Pub/Sub 活动。不要使用 、 或 之类的日志逐项叙述执行过程。
request startedquerying databaserequest completed指标用于聚合计数和等级,trace 用于呈现调用流和耗时,日志用于提供调查单个事件所需的上下文。
Emit structured logs
发出结构化日志
Keep the message stable and put variable data in fields:
typescript
import log from "encore.dev/log";
log.info("order rejected", {
event: "order.rejected",
orderId,
productId,
reason: "insufficient_inventory",
requestedQuantity,
availableQuantity,
});Avoid interpolating identifiers into the message. Stable messages can be grouped, while fields remain searchable.
For events used by dashboards, alerts, or automation, include a stable field. Prefer , such as or . Diagnostic logs do not require an event name.
event<domain>.<past-tense-event>payment.authorizedsubscription.cancelledKeep each field name and type consistent across events. Prefer numeric values with explicit units and enum-like values over formatted prose:
typescript
log.info("payment authorized", {
event: "payment.authorized",
amountMinorUnits: 14900,
currency: "SEK",
});保持消息稳定,并将可变数据放在字段中:
typescript
import log from "encore.dev/log";
log.info("order rejected", {
event: "order.rejected",
orderId,
productId,
reason: "insufficient_inventory",
requestedQuantity,
availableQuantity,
});避免将标识符插入消息中。稳定的消息可用于分组,而字段仍可搜索。
对于供仪表板、告警或自动化使用的事件,请包含稳定的 字段。优先使用 格式,例如 或 。诊断日志不需要事件名称。
event<domain>.<past-tense-event>payment.authorizedsubscription.cancelled确保每个事件中的字段名称和类型保持一致。相比格式化文本,优先使用带明确单位的数值和类似枚举的值:
typescript
log.info("payment authorized", {
event: "payment.authorized",
amountMinorUnits: 14900,
currency: "SEK",
});Choose a level
选择级别
- : an unexpected failure prevented an operation from completing
error - : the application recovered or continued in a degraded state
warn - : a meaningful, relatively low-volume business event
info - : diagnostic detail not required for normal operation
debug - : high-volume internal state
trace
Expected outcomes such as validation failures, missing resources, rejected logins, or declined payments are not events. Use their business meaning to choose a level.
errorThe default minimum level is . Configure in before adding or calls to frequently executed code.
tracelog_levelencore.appdebugtrace- :意外故障导致操作无法完成
error - :应用已恢复,或以降级状态继续运行
warn - :有意义且日志量相对较低的业务事件
info - :正常运行时不需要的诊断细节
debug - :高日志量的内部状态
trace
预期结果,例如验证失败、资源不存在、登录被拒或付款被拒,不属于 事件。应根据其业务含义选择级别。
error默认最低日志级别为 。在向高频执行的代码添加 或 调用之前,请先在 中配置 。
tracedebugtraceencore.applog_levelRecord errors once
只记录一次错误
errorwarntypescript
try {
await chargeCustomer(customerId, amount);
} catch (err) {
log.error(err, "payment authorization failed", {
customerId,
amountMinorUnits: amount,
currency,
});
throw err;
}Passing the original error preserves its type, message, stack trace, and cause. Converting it to a string discards that information.
Log a propagated failure at the layer that owns the recovery decision and has the domain context to describe its impact. A lower layer should log only when it handles or suppresses the error, retries, detects an invariant violation, or holds context that propagation will lose.
errorwarntypescript
try {
await chargeCustomer(customerId, amount);
} catch (err) {
log.error(err, "payment authorization failed", {
customerId,
amountMinorUnits: amount,
currency,
});
throw err;
}传入原始错误可保留其类型、消息、堆栈跟踪和 cause。将其转换为字符串会丢失这些信息。
应在负责恢复决策且拥有领域上下文、能够描述其影响的层记录传播上来的故障。较低层只有在处理或抑制错误、执行重试、检测到不变量违规,或持有继续传播后会丢失的上下文时,才应记录日志。
Add shared context
添加共享上下文
Use when several events from one domain operation share fields:
log.with()typescript
const logger = log.with({ importId, tenantId });
logger.info("user import completed", { succeededCount, failedCount });
logger.warn("user import row rejected", { rowNumber, reason: "invalid_email" });Encore already attaches the service, endpoint, trace ID, and authenticated user ID to request logs. Do not add duplicate copies.
当同一领域操作产生的多个日志事件共享一组字段时,使用 :
log.with()typescript
const logger = log.with({ importId, tenantId });
logger.info("user import completed", { succeededCount, failedCount });
logger.warn("user import row rejected", { rowNumber, reason: "invalid_email" });Encore 已经将 service、endpoint、trace ID 和 authenticated user ID 附加到请求日志中。不要重复添加这些信息。
Protect sensitive data
保护敏感数据
Encore does not redact log fields. Never log credentials, tokens, session identifiers, cookies, authorization headers, secret configuration, payment details, or complete request and response objects.
Prefer internal identifiers over personal data. Use a stable non-reversible fingerprint when correlation requires a value that should not be stored.
The API option redacts request and response payloads from traces; it does not redact values passed to .
sensitivelogEncore 不会对日志字段进行脱敏。绝不记录凭据、token、会话标识符、cookie、Authorization 请求头、机密配置、支付详情,或完整的请求与响应对象。
优先使用内部标识符,而不是个人数据。当关联需要某个不应存储的值时,使用稳定且不可逆的指纹。
sensitivelogControl volume
控制日志量
Summarize batches and long-running operations with outcomes, counts, and durations. Avoid one log per item unless each failure requires investigation.
Log selected metadata from large values rather than complete provider responses, records, configuration objects, arrays, or document bodies. Bound previews and review them for sensitive data before logging.
When reviewing an existing application, check loops, Pub/Sub subscribers, middleware, and frequently called helpers first. A small number of these call sites often produces most of the log volume.
See the Encore.ts logging guide and API reference.
encore.dev/log使用结果、数量和持续时间汇总批处理和长时间运行的操作。除非每个失败都需要调查,否则避免为每个条目记录一条日志。
对于大型值,仅记录精选的元数据,而不是完整的服务提供方响应、记录、配置对象、数组或文档正文。应限制预览内容的长度,并在记录前检查其中是否含有敏感数据。
审查现有应用时,应先检查循环、Pub/Sub 订阅者、中间件和频繁调用的辅助函数。这些调用点中的少数几个通常会产生大部分日志量。