# Add Structured Logging to a Temporal TypeScript Worker

Yes. An agent replaces console.log in your Temporal Activities and Workflows with the SDK's context loggers and a JSON sink on the Worker, then opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-structured-logging/temporal/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads where logs are written today and what context each line is missing. In a project like temporalio/money-transfer-project-template-ts, `src/activities.ts` has three Activities, `withdraw`, `deposit` and `refund`, each starting with a `console.log` template string such as `Withdrawing $${details.amount} from account ${details.sourceAccount}.\n\n` before calling the mock `BankingService` in `src/banking-client.ts`. `src/workflows.ts` runs `moneyTransfer` with `proxyActivities` (a retry policy of up to 500 attempts with `InvalidAccountError` and `InsufficientFundsError` non-retryable, `startToCloseTimeout` of one minute) and logs nothing, not even when the deposit fails and a refund is attempted. `src/worker.ts` creates a `NativeConnection` from `loadClientConnectConfig` and a `Worker` on the `money-transfer` task queue with no `Runtime` configuration, so the SDK's default logger prints to the console. `package.json` pins every `@temporalio/*` package at `~1.14.1`, tests run with `mocha` over `src/mocha/*.test.ts` using `MockActivityEnvironment` and `TestWorkflowEnvironment.createLocal()`, and there is no `.github` directory.

Activities get the Activity logger. Each `console.log` becomes `Context.current().log.info('Withdrawing', { amount: details.amount, sourceAccount: details.sourceAccount, referenceId: details.referenceId })` with `Context` imported from `@temporalio/activity`, and the same for deposit and refund. That logger adds the Activity's own context, including the Workflow id, Activity type and attempt number, to every entry, so a retried withdrawal is distinguishable from its first try without any code in the Activity knowing about retries. The `\n\n` padding and the dollar formatting go; the amount is a field, not prose.

Workflows get the Workflow logger. `src/workflows.ts` imports `log` from `@temporalio/workflow` and logs `info` when the transfer starts, `warn` when the deposit fails and a refund begins, and `error` when the refund also fails, each with `referenceId`, `sourceAccount` and `targetAccount` as fields. The Workflow logger is replay-safe: entries are not re-emitted when the Worker replays history, so the counts stay honest. Workflow failures still carry the same `ApplicationFailure` messages as before.

The sink is set once in `src/worker.ts`. Before `Worker.create`, the agent calls `Runtime.install` with a `DefaultLogger` whose function writes one JSON object per line to stdout: `level`, `message`, a millisecond `timestamp` from the entry's nanosecond stamp, and every field in `meta`, with the level read from a `LOG_LEVEL` environment variable defaulting to `INFO`. `src/client.ts` keeps its `console.log` lines because it is a one-shot script a person runs from a terminal. The agent runs `npm install`, `npm run lint`, `npm run build` and `npm test` in its sandbox, where the Workflow test downloads the Temporal dev server, and includes the output and three sample log lines from the Activity test run.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Replace console.log with structured logging in this Temporal TypeScript project. Read package.json, src/activities.ts, src/workflows.ts, src/worker.ts, src/client.ts, src/banking-client.ts and the tests under src/mocha first. In Activities use Context.current().log from @temporalio/activity with the amount, accounts and reference id as fields rather than in the message. In the Workflow use log from @temporalio/workflow at start, on deposit failure before the refund, and on refund failure, with the same fields. In worker.ts install a Runtime with a DefaultLogger that writes one JSON object per line to stdout (level, message, millisecond timestamp, and the entry's meta), with the level from a LOG_LEVEL environment variable defaulting to INFO. Leave the client script's console output as it is. Do not change the retry policy, timeouts or failure messages. Run npm install, npm run lint, npm run build and npm test, include the output and a few sample log lines, and open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `src/activities.ts` (three log calls and one import), `src/workflows.ts` (one import and three log calls) and `src/worker.ts` (the `Runtime.install` block with the JSON logger). `src/client.ts`, `src/banking-client.ts`, `src/shared.ts`, the tests and `package.json` are untouched, because the logger comes from packages already installed.

The description shows a few JSON lines as the Worker now prints them, with the Workflow id and attempt the SDK attached, and quotes the ESLint, `tsc` and Mocha results. The full command output is in the transcript at `GET /o/{org}/sessions/{id}/messages`.

Before merging, a reviewer checks the field names against what their log pipeline expects, decides whether `LOG_LEVEL` should also gate the SDK's own Core logs, and whether the client script should use the same format when it runs in CI. A follow-up message to the same session can make either change.

## Run it on every Worker onboarded to central logging

A team that moves Workers onto a shared log pipeline one at a time sends `POST /o/{org}/sessions` with this prompt for each repository, naming the field names the pipeline expects in `input` and the repository in `resources`. Each run reads that Worker's own Activities and Workflows, so a project with twenty Activities gets twenty converted calls and a project that already has a `Runtime` gets only the logger change.

A `request_id` that is a UUID v5 of the repository's full name makes a retried call return the run already started. The key's `webhook_url` delivers `run.completed` with the `session_url`, so a handler can post each pull request link to the team's channel as it lands.

## Why run it on Rush?

Converting log lines is tedious and the Temporal part is subtle: an Activity log needs the attempt number, a Workflow log must not repeat on replay, and the sink has to be installed before the Worker starts. The agent does all three in a sandbox with the SDK version the lockfile pins, runs the tests that spin up a real dev server, and keeps the output.

The pull request carries sample lines in the new format and the passing test run, so a reviewer checks field names rather than running a Worker to see what it prints. Many Workers can be converted at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Why not keep console.log and parse it in the pipeline?

Because the lines would still lack the Workflow id, run id, Activity type and attempt number, which the SDK's loggers attach for free. Those fields are what make a failed transfer searchable; parsing prose cannot recover them.

### Will Workflow logs appear twice during replay?

No. The logger from `@temporalio/workflow` suppresses entries while the Worker is replaying history, so each log line is emitted once per real execution of that code. That is the reason to use it rather than importing a logging library into Workflow code.

### Does this change how the tests run?

No. `MockActivityEnvironment` supplies an Activity context, so `Context.current().log` works in the Activity tests, and `TestWorkflowEnvironment.createLocal()` runs the Worker with the same `Runtime`. The agent runs `npm test` and includes the result; the Workflow test needs network access to download the Temporal dev server.

### Where do the SDK's own logs go?

Through the same `DefaultLogger`, so Worker lifecycle messages come out as JSON too. The `LOG_LEVEL` variable sets the threshold for everything the logger receives; the pull request notes how to forward the Rust Core's logs with the Runtime's telemetry options if you want those as well.

## More Temporal jobs

- [Add Cancellation Handling to a Temporal Workflow](https://getrush.ai/run/add-workflow-cancellation/temporal/)
- [Add Timeouts to a Temporal TypeScript Workflow](https://getrush.ai/run/add-workflow-timeouts/temporal/)
- [Version a Running Temporal Workflow Safely](https://getrush.ai/run/add-workflow-versioning/temporal/)

## The same job on other stacks

- [Add Structured JSON Logging to a Tokio Server](https://getrush.ai/run/add-structured-logging/tokio/)
- [Add Structured Logging to a tRPC API](https://getrush.ai/run/add-structured-logging/trpc/)
- [Add Structured JSON Logging to a Vapor App](https://getrush.ai/run/add-structured-logging/vapor/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
