logging

Используется при добавлении логов, отладке или работе с Logger в SDK и среде выполнения контейнера. Охватывает шаблон внедрения через конструктор, дочерние логгеры,…

npx skills add https://github.com/cloudflare/sandbox-sdk --skill logging

Logging

Pattern: Explicit Constructor Injection

Loggers are passed explicitly via constructor injection throughout the codebase. There is no global/ambient logger.

import type { Logger } from '@repo/shared';

class MyService {
  constructor(private logger: Logger) {}

  async doWork(context: WorkContext) {
    const childLogger = this.logger.child({ operation: 'work' });
    childLogger.info('Working', { context });
  }
}

Child loggers

Use logger.child({ ... }) to attach structured context that will appear on every log line from that child. Prefer child loggers at the boundary of a unit of work (request, operation, session) rather than re-passing context on every call.

Configuration

Two environment variables, both read once at startup:

VarValuesPurpose
SANDBOX_LOG_LEVELdebug | info | warn | errorMinimum level emitted
SANDBOX_LOG_FORMATjson | prettyOutput format

Use json in production (machine-parseable) and pretty for local dev.

In Tests

Use createNoOpLogger() from @repo/shared to silence logging in tests:

import { createNoOpLogger } from '@repo/shared';

const service = new MyService(createNoOpLogger());

Don't construct real loggers in unit tests — they add noise and can mask real failures with log output.

When Adding Logs

  • Log at info for significant lifecycle events (operation started/completed)
  • Log at debug for fine-grained tracing (request bodies, intermediate state)
  • Log at warn for recoverable anomalies
  • Log at error for failures that surface to the caller; include the error object as structured context: logger.error('Failed', { err })
  • Pass structured context as the second argument, not via string interpolation

Больше skills от cloudflare

workerd-api-review
cloudflare
Оптимизация производительности, дизайн и совместимость API, уязвимости безопасности и соответствие стандартам для рецензирования кода workerd. Охватывает tcmalloc-совместимые…
official
workerd-safety-review
cloudflare
Паттерны безопасности памяти, потокобезопасности, конкурентности и критического обнаружения для ревью кода workerd. Охватывает граничные риски V8/KJ, управление временем жизни,…
official
module-registry
cloudflare
Загружать при работе с реестром модулей в workerd — чтение, изменение, отладка или проверка разрешения модулей, компиляции, оценки или регистрации…
official
reproduce
cloudflare
Воспроизвести проблему из репозитория cloudflare/agents на GitHub, создав минимальный проект Agents/Worker и развернув его на временном аккаунте Cloudflare, затем сообщить…
official
local-explorer
cloudflare
Как добавлять продукты/ресурсы в локальный обозреватель или локальный API. Используйте при реализации новых локальных API или маршрутов пользовательского интерфейса в…
official
commit-categories
cloudflare
Правила категоризации коммитов для журналов изменений и сводок «что нового». ДОЛЖНЫ быть загружены перед категоризацией коммитов в командах changelog или whats-new. Предоставляет…
official
architecture
cloudflare
Используйте при первом знакомстве с кодовой базой, добавлении нового метода клиента, добавлении нового обработчика/сервиса контейнера или понимании того, как проходит запрос…
official
changesets
cloudflare
Используется при создании changeset, подготовке релиза или обновлении версий. Охватывает, на какие пакеты ссылаться, как писать описания changeset для пользователей,…
official