Skip to content

Commit

Permalink
Migrate logs in playwright package (#574)
Browse files Browse the repository at this point in the history
Move logger init and close from ReplayReporter in test-utils to ReplayPlaywrightReporter.
  • Loading branch information
callingmedic911 authored Jul 1, 2024
1 parent c9b0400 commit 10fc3f2
Show file tree
Hide file tree
Showing 5 changed files with 119 additions and 116 deletions.
13 changes: 7 additions & 6 deletions packages/playwright/src/fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
} from "./playwrightTypes";
import { getServerPort } from "./server";
import { captureRawStack, filteredStackTrace } from "./stackTrace";
import { logger } from "@replay-cli/shared/logger";

function isErrorWithCode<T extends string>(error: unknown, code: T): error is { code: T } {
return !!error && typeof error === "object" && "code" in error && error.code === code;
Expand Down Expand Up @@ -169,7 +170,7 @@ export async function replayFixture(
}
}

debug("Setting up replay fixture");
logger.info("ReplayFixture:SettingUp");

const expectSteps = new Set<string>();
const ignoredSteps = new Set<string>();
Expand Down Expand Up @@ -227,7 +228,7 @@ export async function replayFixture(
// it's not worth it when a convenient API is available though
// even when the issue gets fixed, it's still a good idea to catch those errors here and `debug` them
// they can't be *logged* here because that interferes with the active reporter output
debug("Failed to add annotation: %o", e);
logger.error("ReplayFixture:FailedToAddAnnotation", { error: e });
}
});
})
Expand Down Expand Up @@ -287,7 +288,7 @@ export async function replayFixture(
})
);
} catch (wsError) {
debug("Failed to send error to reporter", wsError);
logger.error("ReplayFixture:FailedToSendErrorToReporter", { wsError });
}
}
}
Expand Down Expand Up @@ -326,7 +327,7 @@ export async function replayFixture(
},
}).catch(err => {
// this should never happen since `handlePlaywrightEvent` should always catch errors internally and shouldn't throw
debug("Failed to add step:start for an expect: %o", err);
logger.error("ReplayFixture:FailedToAddExpectStep", { error: err });
});

return step;
Expand All @@ -350,7 +351,7 @@ export async function replayFixture(
},
}).catch(err => {
// this should never happen since `handlePlaywrightEvent` should always catch errors internally and shouldn't throw
debug("Failed to add step:end for an expect: %o", err);
logger.error("ReplayFixture:FailedToAddExpectStepEnd", { error: err });
});
}
};
Expand Down Expand Up @@ -439,7 +440,7 @@ export function addReplayFixture() {
const testTypeSymbol = Object.getOwnPropertySymbols(test).find(s => s.description === "testType");
const fixtures = testTypeSymbol ? (test as any)[testTypeSymbol]?.fixtures : null;
if (!fixtures) {
debug("Failed to inject replay fixture");
logger.error("ReplayFixture:FailedToInject");
return;
}

Expand Down
31 changes: 18 additions & 13 deletions packages/playwright/src/reporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
ReplayReporterConfig,
TestMetadataV2,
} from "@replayio/test-utils";
import dbg from "debug";
import { readFileSync } from "fs";
import path from "path";
import { WebSocketServer } from "ws";
Expand All @@ -23,9 +22,8 @@ import { getRuntimePath } from "@replay-cli/shared/runtime/getRuntimePath";
import { FixtureStepStart, ParsedErrorFrame, TestExecutionIdData } from "./fixture";
import { StackFrame } from "./playwrightTypes";
import { getServerPort, startServer } from "./server";

const debug = dbg("replay:playwright:reporter");
const pluginVersion = require("@replayio/playwright/package.json").version;
import { initLogger, logger } from "@replay-cli/shared/logger";
import packageJson from "../package.json";

export function getMetadataFilePath(workerIndex = 0) {
return getMetadataFilePathBase("PLAYWRIGHT", workerIndex);
Expand Down Expand Up @@ -81,6 +79,7 @@ class ReplayPlaywrightReporter implements Reporter {
private _foundReplayBrowser = false;

constructor(config: ReplayPlaywrightConfig) {
initLogger(packageJson.name, packageJson.version);
if (!config || typeof config !== "object") {
throw new Error(
`Expected an object for @replayio/playwright/reporter configuration but received: ${config}`
Expand All @@ -92,7 +91,7 @@ class ReplayPlaywrightReporter implements Reporter {
{
name: "playwright",
version: undefined,
plugin: pluginVersion,
plugin: packageJson.version,
},
"2.2.0",
{ ...this.config, metadataKey: "PLAYWRIGHT_REPLAY_METADATA" }
Expand All @@ -104,7 +103,6 @@ class ReplayPlaywrightReporter implements Reporter {
process.env.PLAYWRIGHT_REPLAY_CAPTURE_TEST_FILE?.toLowerCase() || "true"
);
const port = getServerPort();
debug(`Starting plugin WebSocket server on ${port}`);
this.wss = startServer({
port,
onStepStart: (test, step) => {
Expand Down Expand Up @@ -269,7 +267,10 @@ class ReplayPlaywrightReporter implements Reporter {
try {
return [filename, readFileSync(filename, "utf8")];
} catch (e) {
debug(`Failed to read playwright test source for: ${filename}`, e);
logger.error("PlaywrightReporter:FailedToReadPlaywrightTestSource", {
filename,
error: e,
});
return [filename, undefined];
}
})
Expand Down Expand Up @@ -322,16 +323,20 @@ class ReplayPlaywrightReporter implements Reporter {
}

async onEnd() {
await this.reporter.onEnd();
if (!this._foundReplayBrowser) {
console.warn(
"[replay.io]: None of the configured projects ran using Replay Chromium. Please recheck your Playwright config and make sure that Replay Chromium is installed. You can install it using `npx replayio install`"
);
try {
await this.reporter.onEnd();
if (!this._foundReplayBrowser) {
console.warn(
"[replay.io]: None of the configured projects ran using Replay Chromium. Please recheck your Playwright config and make sure that Replay Chromium is installed. You can install it using `npx replayio install`"
);
}
} finally {
await logger.close().catch(() => {});
}
}

parseArguments(apiName: string, params: any) {
debug("Arguments: %s %o", apiName, params);
logger.info("PlaywrightReporter:ParseArguments", { apiName, params });
if (!params || typeof params !== "object") {
return [];
}
Expand Down
8 changes: 5 additions & 3 deletions packages/playwright/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ReporterError } from "@replayio/test-utils";
import dbg from "debug";
import { WebSocketServer } from "ws";
import { FixtureEvent, FixtureStepEnd, FixtureStepStart, TestExecutionIdData } from "./fixture";
import { logger } from "@replay-cli/shared/logger";

const debug = dbg("replay:playwright:server");
const debugMessages = debug.extend("messages");
Expand All @@ -17,7 +18,8 @@ export function startServer({
onStepEnd?: (test: TestExecutionIdData, stepEnd: FixtureStepEnd) => void;
onError?: (test: TestExecutionIdData, error: ReporterError) => void;
}) {
debug("Starting server on %d with handlers %o", port, {
logger.info("PlaywrightServer:Starting", {
port,
onStepStart: !!onStepStart,
onStepEnd: !!onStepEnd,
onError: !!onError,
Expand All @@ -26,7 +28,7 @@ export function startServer({
const wss = new WebSocketServer({ port });

wss.on("connection", function connection(ws) {
debug("Connection established");
logger.info("PlaywrightServer:ConnectionEstablished");

ws.on("error", console.error);

Expand Down Expand Up @@ -61,7 +63,7 @@ export function startServer({
throw new Error("Unexpected server listening on pipe or domain socket");
}

debug("Server started on %d", address.port);
logger.info("PlaywrightServer:Started", { port: address.port });

return wss;
}
Expand Down
3 changes: 2 additions & 1 deletion packages/playwright/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
{
"extends": "@replay-cli/tsconfig/base.json",
"compilerOptions": {
"target": "ES2017"
"target": "ES2017",
"resolveJsonModule": true
},
"include": ["src/**/*.ts"],
"references": [
Expand Down
Loading

0 comments on commit 10fc3f2

Please sign in to comment.