Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change the log level and message for replayio logs #582

Merged
merged 7 commits into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/replayio/src/bin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { initLogger } from "@replay-cli/shared/logger";
import { initLogger, logger } from "@replay-cli/shared/logger";
import { exitProcess } from "@replay-cli/shared/process/exitProcess";
import { setUserAgent } from "@replay-cli/shared/userAgent";
import { name, version } from "../package.json";
Expand Down Expand Up @@ -27,6 +27,7 @@ finalizeCommander();
// avoid ERR_UNHANDLED_REJECTION from being printed to the console
process.on("uncaughtException", async error => {
if (error.name !== "UnhandledPromiseRejection") {
logger.error("UncaughtException", { error });
console.error(error);
}

Expand Down
2 changes: 2 additions & 0 deletions packages/replayio/src/commands/record.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { launchBrowser } from "../utils/browser/launchBrowser";
import { reportBrowserCrash } from "../utils/browser/reportBrowserCrash";
import { registerCommand } from "../utils/commander/registerCommand";
import { confirm } from "../utils/confirm";
import { logger } from "@replay-cli/shared/logger";

registerCommand("record", { checkForRuntimeUpdate: true, requireAuthentication: true })
.argument("[url]", `URL to open (default: "about:blank")`)
Expand All @@ -38,6 +39,7 @@ async function record(url: string = "about:blank") {
await launchBrowser(url, { processGroupId });
} catch (error) {
if (error instanceof ProcessError) {
logger.error("Record:BrowserCrash", { error: error.stderr });
const { errorLogPath, uploaded } = await reportBrowserCrash(error.stderr);

console.log("\nSomething went wrong while recording. Try again.");
Expand Down
2 changes: 2 additions & 0 deletions packages/replayio/src/commands/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { checkForNpmUpdate } from "../utils/initialization/checkForNpmUpdate";
import { checkForRuntimeUpdate } from "../utils/initialization/checkForRuntimeUpdate";
import { promptForNpmUpdate } from "../utils/initialization/promptForNpmUpdate";
import { installLatestRelease } from "../utils/installation/installLatestRelease";
import { logger } from "@replay-cli/shared/logger";

registerCommand("update", {
checkForRuntimeUpdate: false,
Expand Down Expand Up @@ -41,6 +42,7 @@ async function update() {

await exitProcess(0);
} catch (error) {
logger.error("Update:Failed", { error });
console.error(error);

await exitProcess(1);
Expand Down
6 changes: 5 additions & 1 deletion packages/replayio/src/commands/upload-source-maps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { uploadSourceMaps as uploadSourceMapsExternal } from "@replayio/sourcema
import { replayApiServer } from "../config";
import { logPromise } from "../utils/async/logPromise";
import { registerCommand } from "../utils/commander/registerCommand";
import { logger } from "@replay-cli/shared/logger";

registerCommand("upload-source-maps <paths...>", { requireAuthentication: true })
.description("Upload source-maps for a Workspace")
Expand Down Expand Up @@ -56,7 +57,10 @@ async function uploadSourceMaps(
messages: {
pending: "Uploading source maps...",
success: "Source maps uploaded",
failed: error => `Source maps upload failed:\n${error}`,
failed: error => {
logger.error("UploadSourceMaps:Failed", { error });
return `Source maps upload failed:\n${error}`;
},
},
});

Expand Down
2 changes: 1 addition & 1 deletion packages/replayio/src/utils/browser/getRunningProcess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export async function getRunningProcess() {
if (processes.length > 0) {
const match = processes[0];

logger.debug(`Browser process already running at ${highlight(match.pid)}`);
logger.debug("GetRunningProcess:AlreadyRunning", { pid: match.pid });

return match;
}
Expand Down
8 changes: 4 additions & 4 deletions packages/replayio/src/utils/browser/launchBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ export async function launchBrowser(
};

if (!existsSync(browserExecutablePath)) {
logger.debug(`Replay browser not found at: ${browserExecutablePath}`);
logger.error("LaunchBrowser:BrowserNotFound", { browserExecutablePath });
throw new Error(`Replay browser not found at: ${browserExecutablePath}`);
}

logger.debug("Launching browser", { args, browserExecutablePath, processOptions });
logger.info("LaunchBrowser:Launching", { args, browserExecutablePath, processOptions });

// Wait until the user quits the browser process OR
// until the user presses a key to continue (in which case, we will kill the process)
Expand Down Expand Up @@ -75,10 +75,10 @@ export async function launchBrowser(
}
},
printStderr: (text: string) => {
logger.debug(`${stderrPrefix("stderr")} ${text}`);
logger.error("LaunchBrowser:Stderr", { text });
},
printStdout: (text: string) => {
logger.debug(`${stdoutPrefix("stdout")} ${text}`);
logger.debug("LaunchBrowser:Stdout", { text });
},
});

Expand Down
2 changes: 1 addition & 1 deletion packages/replayio/src/utils/browser/reportBrowserCrash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export async function reportBrowserCrash(stderr: string) {
};
}
} catch (error) {
logger.debug("Crash data failed to be uploaded", { error });
logger.error("ReportBrowserCrash:FailedToUpload", { error });
}

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export type AuthInfo = {
};

export async function fetchViewerFromGraphQL(accessToken: string): Promise<AuthInfo> {
logger.debug("Fetching viewer info from GraphQL");
logger.info("FetchViewerFromGraphQL:Start");

const { data, errors } = await queryGraphQL(
"ViewerInfo",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const checkForNpmUpdate = createAsyncFunctionWithTracking(
toVersion: latestVersion,
};
} catch (error) {
logger.debug("Failed to check for npm update", { error });
logger.error("CheckForNpmUpdate:Failed", { error });
}

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ export const checkForRuntimeUpdate = createAsyncFunctionWithTracking(
latestRelease = await getLatestRelease();
latestBuildId = latestRelease?.buildId ?? null;
if (latestBuildId == null) {
logger.debug("No release found; skipping update check");
logger.info("CheckForRuntimeUpdate:NoReleaseFound");

return {
hasUpdate: undefined,
};
}
} catch (error) {
logger.debug("Release check failed", { error });
logger.error("CheckForRuntimeUpdate:Failed", { error });

return {
hasUpdate: undefined,
Expand All @@ -47,11 +47,7 @@ export const checkForRuntimeUpdate = createAsyncFunctionWithTracking(
}

const { buildId: currentBuildId } = getCurrentRuntimeMetadata("chromium") ?? {};
if (currentBuildId) {
logger.debug(`Current build id: ${currentBuildId}`);
} else {
logger.debug("Installed version metadata not found");
}
logger.debug("CheckForRuntimeUpdate:CurrentBuild", { currentBuildId, latestBuildId });

return {
hasUpdate: currentBuildId !== latestBuildId,
Expand Down
4 changes: 2 additions & 2 deletions packages/replayio/src/utils/installation/getLatestReleases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { Release } from "./types";
const { architecture, platform, runtime } = runtimeMetadata;

export async function getLatestRelease() {
logger.debug("Fetching release metadata");
logger.debug("GetLatestRelease:Start");

const response = await fetch(`${replayAppHost}/api/releases`);
const json = (await response.json()) as Release[];
Expand All @@ -19,7 +19,7 @@ export async function getLatestRelease() {
(release.architecture === architecture || release.architecture === "unknown")
);

logger.debug("Latest release", latestRelease);
logger.debug("GetLatestRelease:LatestRelease", { latestRelease });
assert(latestRelease, `No release found for ${platform}:${runtime}`);

return latestRelease;
Expand Down
23 changes: 13 additions & 10 deletions packages/replayio/src/utils/installation/installLatestRelease.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type Result = {

export const installLatestRelease = createAsyncFunctionWithTracking(
async function installLatestRelease(): Promise<Result | undefined> {
logger.info("InstallLatestRelease:Start");
const runtimeBaseDir = getReplayPath("runtimes");
const runtimePath = getReplayPath("runtimes", runtimeMetadata.destinationName);
const downloadFilePath = getReplayPath("runtimes", runtimeMetadata.downloadFileName);
Expand All @@ -38,17 +39,17 @@ export const installLatestRelease = createAsyncFunctionWithTracking(

progress.setPending("Processing downloaded browser archive");

logger.debug(`Removing previous installation at ${runtimePath}`);
logger.info("InstallLatestRelease:RemovingPreviousInstallation", { runtimePath });
rmSync(runtimePath, { force: true, recursive: true });

ensureDirSync(runtimeBaseDir);

logger.debug(`Writing downloaded file data to ${downloadFilePath}`);
logger.info("InstallLatestRelease:WritingDownloadFile", { downloadFilePath });
writeFileSync(downloadFilePath, buffers);

extractBrowserArchive(runtimeBaseDir, runtimePath);

logger.debug(`Deleting downloaded file ${downloadFilePath}`);
logger.info("InstallLatestRelease:DeletingDownloadedFile", { downloadFilePath });
unlinkSync(downloadFilePath);

// This seems unnecessary, but we've always done it (and changing it would break legacy CLI compat)
Expand All @@ -66,7 +67,7 @@ export const installLatestRelease = createAsyncFunctionWithTracking(
const latestVersion = latestRelease.version;

// Write version metadata to disk so we can compare against the latest release and prompt to update
logger.debug(`Saving release metadata to ${metadataPath}`);
logger.info("InstallLatestRelease:SavingMetadata", { metadataPath });
writeToCache<MetadataJSON>(metadataPath, {
chromium: {
buildId: latestBuildId,
Expand All @@ -82,7 +83,7 @@ export const installLatestRelease = createAsyncFunctionWithTracking(
forkedVersion: latestVersion,
};
} catch (error) {
logger.debug("Browser installation failed", { error });
logger.error("InstallLatestRelease:Failed", { error });

progress.setFailed(
"Something went wrong installing the Replay browser. Please try again later."
Expand Down Expand Up @@ -124,7 +125,7 @@ async function downloadReplayFile({ onRetry }: { onRetry?: (attempt: number) =>
const buffers = await new Promise<Buffer[] | null>((resolve, reject) => {
const request = get(options, response => {
if (response.statusCode != 200) {
logger.debug(`Download received status code ${response.statusCode}, retrying...`);
logger.debug("DownloadReplayFile:UnexpectedStatus", { statusCode: response.statusCode });
request.destroy();
resolve(null);
return;
Expand All @@ -135,7 +136,7 @@ async function downloadReplayFile({ onRetry }: { onRetry?: (attempt: number) =>
response.on("end", () => resolve(buffers));
});
request.on("error", error => {
logger.debug(`Download error ${error}, retrying...`);
logger.debug("DownloadReplayFile:Error", { error });
request.destroy();
resolve(null);
});
Expand All @@ -150,14 +151,16 @@ async function downloadReplayFile({ onRetry }: { onRetry?: (attempt: number) =>
}

async function extractBrowserArchive(runtimeBaseDir: string, downloadFilePath: string) {
logger.debug(`Extracting archived file at ${downloadFilePath}`);
logger.info(`ExtractBrowserArchive:Extracting`, { downloadFilePath });

const tarResult = spawnSync("tar", ["xf", runtimeMetadata.downloadFileName], {
cwd: runtimeBaseDir,
});
if (tarResult.status !== 0) {
logger.debug(`Failed to extract ${downloadFilePath}`);
logger.debug(String(tarResult.stderr));
logger.error("ExtractBrowserArchive:Failed", {
downloadFilePath,
stderr: String(tarResult.stderr),
});

throw new Error("Unable to extract browser archive");
}
Expand Down
7 changes: 6 additions & 1 deletion packages/shared/src/process/exitTask.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { close as finalizeLaunchDarkly } from "../launch-darkly/close";
import { mixpanelAPI } from "../mixpanel/mixpanelAPI";
import { logger } from "../logger";

export type ExitTask = () => Promise<void>;

export const exitTasks: ExitTask[] = [finalizeLaunchDarkly, () => mixpanelAPI.close()];
export const exitTasks: ExitTask[] = [
finalizeLaunchDarkly,
() => mixpanelAPI.close(),
() => logger.close(),
];

export function registerExitTask(exitTask: ExitTask) {
exitTasks.push(exitTask);
Expand Down