Skip to content

Commit

Permalink
Include serialised FormData in debug logs (#6854)
Browse files Browse the repository at this point in the history
* Include serialised FormData in debug logs

* Create bright-deers-rescue.md

* fix tests

* Fix tests

* fix lint
  • Loading branch information
penalosa authored Oct 3, 2024
1 parent 7ca37bc commit 04a8fed
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/bright-deers-rescue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wrangler": patch
---

chore: Include serialised `FormData` in debug logs
40 changes: 37 additions & 3 deletions packages/wrangler/src/__tests__/deploy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
printBundleSize,
printOffendingDependencies,
} from "../deployment-bundle/bundle-reporter";
import { logger } from "../logger";
import { writeAuthConfigFile } from "../user";
import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
import { mockAuthDomain } from "./helpers/mock-auth-domain";
Expand Down Expand Up @@ -80,7 +79,6 @@ describe("deploy", () => {
mockLastDeploymentRequest();
mockDeploymentsListRequest();
msw.use(...mswListNewDeploymentsLatestFull);
logger.loggerLevel = "log";
});

afterEach(() => {
Expand Down Expand Up @@ -248,6 +246,40 @@ describe("deploy", () => {
expect(std.err).toMatchInlineSnapshot(`""`);
});

it("should include serialised FormData in debug logs", async () => {
fs.mkdirSync("./my-worker", { recursive: true });
fs.writeFileSync(
"./my-worker/wrangler.toml",
TOML.stringify({
name: "test-worker",
compatibility_date: "2022-01-12",
vars: { xyz: 123 },
}),
"utf-8"
);
writeWorkerSource({ basePath: "./my-worker" });
mockUploadWorkerRequest({
expectedScriptName: "test-worker",
expectedBindings: [
{
json: 123,
name: "xyz",
type: "json",
},
],
expectedCompatibilityDate: "2022-01-12",
});
mockSubDomainRequest();

vi.stubEnv("WRANGLER_LOG", "debug");
vi.stubEnv("WRANGLER_LOG_SANITIZE", "false");

await runWrangler("deploy ./my-worker/index.js");
expect(std.debug).toContain(
`{"main_module":"index.js","bindings":[{"name":"xyz","type":"json","json":123}],"compatibility_date":"2022-01-12","compatibility_flags":[]}`
);
});

it("should support wrangler.jsonc", async () => {
fs.mkdirSync("./my-worker", { recursive: true });
fs.writeFileSync(
Expand Down Expand Up @@ -4105,7 +4137,9 @@ addEventListener('fetch', event => {});`
});

it("debug log level", async () => {
logger.loggerLevel = "debug";
vi.stubEnv("WRANGLER_LOG", "debug");
vi.stubEnv("WRANGLER_LOG_SANITIZE", "false");

await runWrangler("deploy");

const diffRegexp = /^ [+=-]/;
Expand Down
10 changes: 9 additions & 1 deletion packages/wrangler/src/cfetch/internal.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import assert from "node:assert";
import { fetch, File, Headers, Response } from "undici";
import { fetch, File, FormData, Headers, Response } from "undici";
import { version as wranglerVersion } from "../../package.json";
import { getCloudflareApiBaseUrl } from "../environment-variables/misc-variables";
import { UserError } from "../errors";
Expand Down Expand Up @@ -41,6 +41,14 @@ export async function performApiFetch(
logger.debugWithSanitization("HEADERS:", JSON.stringify(logHeaders, null, 2));

logger.debugWithSanitization("INIT:", JSON.stringify({ ...init }, null, 2));
if (init.body instanceof FormData) {
logger.debugWithSanitization(
"BODY:",
await new Response(init.body).text(),
null,
2
);
}
logger.debug("-- END CF API REQUEST");
return await fetch(`${getCloudflareApiBaseUrl()}${resource}${queryString}`, {
method,
Expand Down
24 changes: 22 additions & 2 deletions packages/wrangler/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ const getLogLevelFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_LOG",
});

const warnOnce = (() => {
let logged = false;

return (...args: Parameters<typeof console.warn>) => {
if (!logged) {
console.warn(...args);
logged = true;
}
};
})();

function getLoggerLevel(): LoggerLevel {
const fromEnv = getLogLevelFromEnv()?.toLowerCase();
if (fromEnv !== undefined) {
Expand All @@ -40,7 +51,7 @@ function getLoggerLevel(): LoggerLevel {
const expected = Object.keys(LOGGER_LEVELS)
.map((level) => `"${level}"`)
.join(" | ");
console.warn(
warnOnce(
`Unrecognised WRANGLER_LOG value ${JSON.stringify(
fromEnv
)}, expected ${expected}, defaulting to "log"...`
Expand All @@ -54,7 +65,16 @@ export type TableRow<Keys extends string> = Record<Keys, string>;
export class Logger {
constructor() {}

loggerLevel = getLoggerLevel();
private overrideLoggerLevel?: LoggerLevel;

get loggerLevel() {
return this.overrideLoggerLevel ?? getLoggerLevel();
}

set loggerLevel(val) {
this.overrideLoggerLevel = val;
}

columns = process.stdout.columns;

debug = (...args: unknown[]) => this.doLog("debug", args);
Expand Down

0 comments on commit 04a8fed

Please sign in to comment.