Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
ccaa86c
Add context method
bgrgicak Apr 15, 2024
0e8b73a
Collect context
bgrgicak Apr 16, 2024
10f5e25
Collect worker metrics as context data
bgrgicak Apr 16, 2024
c127c95
Add context and blueprint to logger API request
bgrgicak Apr 16, 2024
8d89ca4
Rename addFatalErrorListener
bgrgicak Apr 17, 2024
be6446c
Add context and blueprint sections to report
bgrgicak Apr 17, 2024
1f07595
Count tabs instead of all clients
bgrgicak Apr 17, 2024
653735a
Remove debug code
bgrgicak Apr 17, 2024
40e3ab5
Revert url to production
bgrgicak Apr 17, 2024
007ac3f
Merge branch 'trunk' into add/1152-logger-context
bgrgicak Apr 17, 2024
d0a54b8
Refactor logger
bgrgicak Apr 17, 2024
270c7f8
Add log methods
bgrgicak Apr 17, 2024
26ce2cf
Add arg support
bgrgicak Apr 17, 2024
311dc1e
Move reference
bgrgicak Apr 17, 2024
910539b
Add tests
bgrgicak Apr 17, 2024
c37a47e
Address feedback
bgrgicak Apr 17, 2024
868752f
Merge branch 'add/1152-logger-context' into add/log-methods
bgrgicak Apr 17, 2024
a7ea3f2
Parent PR feedback
bgrgicak Apr 17, 2024
4ac444e
Add linter rules
bgrgicak Apr 18, 2024
2aeb4c2
Add comment to addServiceWorkerMessageListener
bgrgicak Apr 18, 2024
23cd042
Remove linter rules
bgrgicak Apr 18, 2024
306d3e2
Merge branch 'add/1152-logger-context' into add/log-methods
bgrgicak Apr 18, 2024
7ea4013
Merge branch 'trunk' into add/1152-logger-context
bgrgicak Apr 19, 2024
6786e9a
Update packages/php-wasm/logger/src/lib/logger.ts
bgrgicak Apr 19, 2024
44c688b
Update packages/php-wasm/logger/src/lib/logger.ts
bgrgicak Apr 19, 2024
0d86ce1
Update packages/php-wasm/logger/src/lib/logger.ts
bgrgicak Apr 19, 2024
e24aafd
Remove worker claim
bgrgicak Apr 19, 2024
6e0b8ee
Merge branch 'add/1152-logger-context' into add/log-methods
bgrgicak Apr 19, 2024
4c01ceb
Add comment about using includeUncontrolled
bgrgicak Apr 19, 2024
551a4ae
Merge branch 'add/1152-logger-context' into add/log-methods
bgrgicak Apr 19, 2024
49f1e03
Merge branch 'trunk' into add/log-methods
bgrgicak Apr 19, 2024
1d6c7d3
Post metrics to controlled clients only
bgrgicak Apr 22, 2024
a5c9ec1
Add log handlers
bgrgicak Apr 22, 2024
5453638
Remove unrelated changes
bgrgicak Apr 22, 2024
b002aed
Log to memory
bgrgicak Apr 23, 2024
0e8a3da
Separate collectors
bgrgicak Apr 23, 2024
c9f9028
Move formatLogEntry to main logger file
bgrgicak Apr 24, 2024
fca0706
Replace context with logs
bgrgicak Apr 24, 2024
89b58bc
Add error to getLogs when logToMemory isn't registered
bgrgicak Apr 24, 2024
ed8dbd9
Fix test
bgrgicak Apr 24, 2024
417c7fb
Disable console logs in tests
bgrgicak Apr 24, 2024
8a09663
Merge branch 'trunk' into add/log-methods
bgrgicak Apr 24, 2024
15589c0
Add linter rules
bgrgicak Apr 24, 2024
a2e9869
Replace console with logger TODO test and fix issues
bgrgicak Apr 24, 2024
de6899d
Remove logger from vite fie
bgrgicak Apr 24, 2024
f0ac462
Remove circular dependencies
bgrgicak Apr 24, 2024
32fa3ef
Fix circular dependencies
bgrgicak Apr 24, 2024
857874b
Fix linter config for tests
bgrgicak Apr 24, 2024
541c6ce
Show logs as lines
bgrgicak Apr 24, 2024
4384405
Add PHPRequestErrorEvent type
bgrgicak Apr 24, 2024
9e77966
Apply suggestions from code review
bgrgicak Apr 24, 2024
6943cd8
Update packages/php-wasm/logger/src/lib/collectors/collect-php-logs.ts
bgrgicak Apr 25, 2024
6923ec3
Rename logWindowError
bgrgicak Apr 25, 2024
684b925
Merge branch 'trunk' into add/log-methods
bgrgicak Apr 25, 2024
afb6849
Fix type
bgrgicak Apr 25, 2024
8006d32
Merge branch 'add/log-methods' into update/console-to-logger
bgrgicak Apr 25, 2024
d68816a
Fix build
bgrgicak Apr 25, 2024
1cca09a
Merge branch 'trunk' into update/console-to-logger
bgrgicak Apr 25, 2024
177583d
Merge branch 'trunk' into update/console-to-logger
bgrgicak Apr 25, 2024
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
8 changes: 7 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"no-inner-declarations": 0,
"no-use-before-define": "off",
"react/prop-types": 0,
"no-console": 0,
"no-console": 1,
"no-empty": 0,
"no-async-promise-executor": 0,
"no-constant-condition": 0,
Expand Down Expand Up @@ -60,6 +60,12 @@
"files": "*.json",
"parser": "jsonc-eslint-parser",
"rules": {}
},
{
"files": "*.spec.ts",
"rules": {
"no-console": 0
}
}
]
}
4 changes: 3 additions & 1 deletion packages/nx-extensions/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
"rules": {
"no-console": 0
}
},
{
"files": ["*.ts", "*.tsx"],
Expand Down
7 changes: 4 additions & 3 deletions packages/php-wasm/fs-journal/src/lib/fs-journal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
} from '@php-wasm/universal';
import type { IsomorphicLocalPHP } from '@php-wasm/universal';
import { Semaphore, basename, joinPaths } from '@php-wasm/util';
import { logger } from '@php-wasm/logger';

export type EmscriptenFS = any;

Expand Down Expand Up @@ -401,7 +402,7 @@ export function normalizeFilesystemOperations(
//
// But that's not a straightforward transformation so let's just not handle
// it for now.
console.warn(
logger.warn(
'[FS Journal] Normalizing a double rename is not yet supported:',
{
current: latter,
Expand Down Expand Up @@ -547,11 +548,11 @@ async function hydrateOp(php: UniversalPHP, op: UpdateFileOperation) {
op.data = await php.readFileAsBuffer(op.path);
} catch (e) {
// Log the error but don't throw.
console.warn(
logger.warn(
`Journal failed to hydrate a file on flush: the ` +
`path ${op.path} no longer exists`
);
console.error(e);
logger.error(e);
}

release();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import {
UniversalPHP,
PHPRequestErrorEvent,
} from '@php-wasm/universal/src/lib/universal-php';
import { UniversalPHP, PHPRequestErrorEvent } from '../../universal';
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These imports were causing circular dependency issues, so I added type declarations.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not great, not terrible 🤷

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can always switch to any 😅

import { Logger } from '../logger';

let lastPHPLogLength = 0;
Expand Down
20 changes: 1 addition & 19 deletions packages/php-wasm/logger/src/test/logger.spec.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,11 @@
import { NodePHP } from '@php-wasm/node';
import { LatestSupportedPHPVersion } from '@php-wasm/universal';
import { Logger, addCrashListener } from '../lib/logger';
import { collectPhpLogs } from '../lib/log-collector';
import { Logger } from '../lib/logger';
import { clearMemoryLogs, logToMemory } from '../lib/log-handlers';

describe('Logger', () => {
let php: NodePHP;
const logger = new Logger([logToMemory]);
beforeEach(async () => {
php = await NodePHP.load(LatestSupportedPHPVersion);
clearMemoryLogs();
});
it('Event listener should work', () => {
const listener = vi.fn();
collectPhpLogs(logger, php);
addCrashListener(logger, listener);
php.dispatchEvent({
type: 'request.error',
error: new Error('test'),
});
expect(listener).toBeCalledTimes(1);

const logs = logger.getLogs();
expect(logs.length).toBe(1);
});
Comment on lines -14 to -26
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test would require a lot of mocking and it's not that useful, so I removed it.


it('Log message should be added', () => {
logger.warn('test');
Expand Down
27 changes: 27 additions & 0 deletions packages/php-wasm/logger/src/universal.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
export interface UniversalPHP {
/**
* Read the content of a file as text.
*
* @param path The path to the file
* @returns string The content of the file
*/
readFileAsText(path: string): Promise<string>;
/**
* Check if a file exists.
*
* @param path The path to the file
* @returns boolean Whether the file exists
*/
fileExists(path: string): Promise<boolean>;

addEventListener(
event: string,
listener: (event: PHPRequestEndEvent | PHPRequestErrorEvent) => void
): void;
}

export interface PHPRequestErrorEvent {
type: 'request.error';
error: Error;
source?: 'request' | 'php-wasm';
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function prependByte(
buffer.set(new Uint8Array(chunk), 1);
chunk = buffer.buffer;
} else {
console.log({ chunk });
log({ chunk });
throw new Error('Unsupported chunk type: ' + typeof chunk);
}
return chunk;
Expand Down
5 changes: 3 additions & 2 deletions packages/php-wasm/node/src/lib/networking/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import * as net from 'net';
import { logger } from '@php-wasm/logger';

export function debugLog(...args: any[]) {
export function debugLog(message: any, ...args: any[]) {
if (process.env['DEV'] && !process.env['TEST']) {
console.log(...args);
logger.log(message, ...args);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { logger } from '@php-wasm/logger';
/*
* An approximate total file size to use when the actual
* total number of bytes is missing.
Expand Down Expand Up @@ -69,7 +70,7 @@ export class EmscriptenDownloadMonitor extends EventTarget {
fileSize = this.#assetsSizes[fileName];
}
if (!(fileName in this.#progress)) {
console.warn(
logger.warn(
`Registered a download #progress of an unregistered file "${fileName}". ` +
`This may cause a sudden **decrease** in the #progress percentage as the ` +
`total number of bytes increases during the download.`
Expand Down Expand Up @@ -156,7 +157,7 @@ export function cloneResponseMonitorProgress(
controller.enqueue(value);
}
} catch (e) {
console.error({ e });
logger.error({ e });
controller.error(e);
break;
}
Expand Down
15 changes: 8 additions & 7 deletions packages/php-wasm/universal/src/lib/base-php.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
UnhandledRejectionsTarget,
} from './wasm-error-reporting';
import { Semaphore, createSpawnHandler, joinPaths } from '@php-wasm/util';
import { logger } from '@php-wasm/logger';

const STRING = 'string';
const NUMBER = 'number';
Expand Down Expand Up @@ -292,14 +293,14 @@ export abstract class BasePHP implements IsomorphicLocalPHP {

const response = await this.#handleRequest();
if (response.exitCode !== 0) {
console.warn(`PHP.run() output was:`, response.text);
logger.warn(`PHP.run() output was:`, response.text);
const error = new PHPExecutionFailureError(
`PHP.run() failed with exit code ${response.exitCode} and the following output: ` +
response.errors,
response,
'request'
) as PHPExecutionFailureError;
console.error(error);
logger.error(error);
throw error;
}
return response;
Expand Down Expand Up @@ -521,7 +522,7 @@ export abstract class BasePHP implements IsomorphicLocalPHP {
#setRequestBody(body: string | Uint8Array) {
let size, contentLength;
if (typeof body === 'string') {
console.warn(
logger.warn(
'Passing a string as the request body is deprecated. Please use a Uint8Array instead. See ' +
'https://github.com/WordPress/wordpress-playground/issues/997 for more details'
);
Expand Down Expand Up @@ -633,8 +634,8 @@ export abstract class BasePHP implements IsomorphicLocalPHP {
// eslint-disable-next-line no-async-promise-executor
exitCode = await new Promise<number>((resolve, reject) => {
errorListener = (e: ErrorEvent) => {
console.error(e);
console.error(e.error);
logger.error(e);
logger.error(e.error);
const rethrown = new Error('Rethrown');
rethrown.cause = e.error;
(rethrown as any).betterMessage = e.message;
Expand Down Expand Up @@ -680,7 +681,7 @@ export abstract class BasePHP implements IsomorphicLocalPHP {
) as string;
const rethrown = new Error(message);
rethrown.cause = err;
console.error(rethrown);
logger.error(rethrown);
throw rethrown;
} finally {
this.#wasmErrorsTarget?.removeEventListener('error', errorListener);
Expand Down Expand Up @@ -785,7 +786,7 @@ export abstract class BasePHP implements IsomorphicLocalPHP {
}
return files;
} catch (e) {
console.error(e, { path });
logger.error(e, { path });
return [];
}
}
Expand Down
4 changes: 3 additions & 1 deletion packages/php-wasm/universal/src/lib/http-cookie-store.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { logger } from '@php-wasm/logger';

/**
* @public
*/
Expand All @@ -20,7 +22,7 @@ export class HttpCookieStore {
.split(';')[0];
this.cookies[name] = value;
} catch (e) {
console.error(e);
logger.error(e);
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion packages/php-wasm/universal/src/lib/load-php-runtime.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { logger } from '@php-wasm/logger';

const RuntimeId = Symbol('RuntimeId');
const loadedRuntimes: Map<number, PHPRuntime> = new Map();
let lastRuntimeId = 0;
Expand Down Expand Up @@ -130,7 +132,7 @@ export async function loadPHPRuntime(
rejectPHP(reason);
// This can happen after PHP has been initialized so
// let's just log it.
console.error(reason);
logger.error(reason);
},
ENV: {},
// Emscripten sometimes prepends a '/' to the path, which
Expand Down
3 changes: 2 additions & 1 deletion packages/php-wasm/universal/src/lib/php-request-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { PHPResponse } from './php-response';
import { PHPRequest, PHPRunOptions } from './universal-php';
import { encodeAsMultipart } from './encode-as-multipart';
import { HttpCookieStore } from './http-cookie-store';
import { logger } from '@php-wasm/logger';

export type RewriteRule = {
match: RegExp;
Expand Down Expand Up @@ -311,7 +312,7 @@ export class PHPRequestHandler {
this.#semaphore.running > 0 &&
request.headers?.['x-request-issuer'] === 'php'
) {
console.warn(
logger.warn(
`Possible deadlock: Called request() before the previous request() have finished. ` +
`PHP likely issued an HTTP call to itself. Normally this would lead to infinite ` +
`waiting as Request 1 holds the lock that the Request 2 is waiting to acquire. ` +
Expand Down
7 changes: 4 additions & 3 deletions packages/php-wasm/universal/src/lib/wasm-error-reporting.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ErrorEvent } from './error-event-polyfill';
import { isExitCodeZero } from './is-exit-code-zero';
import { logger } from '@php-wasm/logger';

type Runtime = {
asm: Record<string, unknown>;
Expand Down Expand Up @@ -143,11 +144,11 @@ export function showCriticalErrorBox(message: string) {
if (message?.trim().startsWith('Program terminated with exit')) {
return;
}
console.log(`${redBg}\n${eol}\n${bold} WASM ERROR${reset}${redBg}`);
logger.log(`${redBg}\n${eol}\n${bold} WASM ERROR${reset}${redBg}`);
for (const line of message.split('\n')) {
console.log(`${eol} ${line} `);
logger.log(`${eol} ${line} `);
}
console.log(`${reset}`);
logger.log(`${reset}`);
}

function extractPHPFunctionsFromStack(stack: string) {
Expand Down
4 changes: 3 additions & 1 deletion packages/php-wasm/web-service-worker/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
"rules": {
"no-console": 0
}
},
{
"files": ["*.ts", "*.tsx"],
Expand Down
3 changes: 2 additions & 1 deletion packages/php-wasm/web/src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { PHPResponse, PHPResponseData } from '@php-wasm/universal';
import * as Comlink from 'comlink';
import { logger } from '@php-wasm/logger';

export type WithAPIState = {
/**
Expand Down Expand Up @@ -133,7 +134,7 @@ function setupTransferHandlers() {
Comlink.transferHandlers.set('FUNCTION', {
canHandle: (obj: unknown): obj is Function => typeof obj === 'function',
serialize(obj: Function) {
console.debug('[Comlink][Performance] Proxying a function');
logger.debug('[Comlink][Performance] Proxying a function');
const { port1, port2 } = new MessageChannel();
Comlink.expose(obj, port1);
return [port2, [port2]];
Expand Down
3 changes: 2 additions & 1 deletion packages/php-wasm/web/src/lib/register-service-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { PhpWasmError } from '@php-wasm/util';
import type { WebPHPEndpoint } from './web-php-endpoint';
import { responseTo } from '@php-wasm/web-service-worker';
import { Remote } from 'comlink';
import { logger } from '@php-wasm/logger';

/**
* Run this in the main application to register the service worker or
Expand Down Expand Up @@ -33,7 +34,7 @@ export async function registerServiceWorker<
}
}

console.debug(`[window][sw] Registering a Service Worker`);
logger.debug(`[window][sw] Registering a Service Worker`);
const registration = await sw.register(scriptUrl, {
type: 'module',
// Always bypass HTTP cache when fetching the new Service Worker script:
Expand Down
Loading