A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor(logging): route console.* through the Logger module
esenginee8fe9767439f
diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex 8a6343550..d7163a1df 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -22,6 +22,7 @@ import { sceneManagerPlugin } from './scenePlugin';import { getDefaultContext } from './context';import { cameraPlugin } from './camera/CameraPlugin';import { PhysicsRuntime } from './physics/PhysicsRuntime';+import { log } from './logger';// =============================================================================// Plugin Interface@@ -253,7 +254,7 @@ export class App {async waitForPhysics(): Promise<void> {if (!this.hasResource(PhysicsRuntime)) {- console.warn('[ESEngine] No PhysicsPlugin installed, waitForPhysics() is a no-op');+ log.warn('app', 'No PhysicsPlugin installed, waitForPhysics() is a no-op');return;}const promise = this.getResource(PhysicsRuntime).initPromise;@@ -472,7 +473,7 @@ export class App {for (let i = this.installed_plugins_.length - 1; i >= 0; i--) {try { this.installed_plugins_[i].cleanup?.(this); } catch (e) {- console.error('[ESEngine] Plugin cleanup error:', e);+ log.error('app', 'Plugin cleanup error', e);}}this.installed_plugins_.length = 0;@@ -480,7 +481,7 @@ export class App {this.installedPluginNames_.clear();for (const entity of this.world_.getAllEntities()) {- try { this.world_.despawn(entity); } catch (e) { console.warn('[App] Shutdown despawn error:', e); }+ try { this.world_.despawn(entity); } catch (e) { log.warn('app', 'Shutdown despawn error', e); }}this.world_.disconnectCpp();@@ -546,7 +547,7 @@ export class App {this.pluginsFinished_ = true;for (const plugin of this.installed_plugins_) {try { plugin.finish?.(this); } catch (e) {- console.error(`[ESEngine] Plugin "${plugin.name ?? 'unknown'}" finish error:`, e);+ log.error('app', `Plugin "${plugin.name ?? 'unknown'}" finish error`, e);}}}@@ -559,7 +560,7 @@ export class App {const name = plugins[i].name;if (name) {if (nameToIndex.has(name)) {- console.warn(`[ESEngine] Duplicate plugin name "${name}" at indices ${nameToIndex.get(name)} and ${i}`);+ log.warn('app', `Duplicate plugin name "${name}" at indices ${nameToIndex.get(name)} and ${i}`);}nameToIndex.set(name, i);}@@ -735,7 +736,7 @@ export class App {}} catch (e) {const name = entry.system._name;- console.error(`[ESEngine] System "${name}" threw an error:`, e);+ log.error('app', `System "${name}" threw an error`, e);if (this.error_handler_) {this.error_handler_(e, name);}diff --git a/sdk/src/asset/AssetPlugin.ts b/sdk/src/asset/AssetPlugin.tsindex e23c3a93b..ca4cb99c4 100644--- a/sdk/src/asset/AssetPlugin.ts+++ b/sdk/src/asset/AssetPlugin.ts@@ -4,6 +4,7 @@ import { Assets as AssetsClass } from './Assets';import { HttpBackend } from './Backend';import { initBuiltinAssetFields } from './AssetFieldRegistry';import { AssetRefCounter } from './AssetRefCounter';+import { log } from '../logger';export type AssetsData = AssetsClass;@@ -18,7 +19,7 @@ export class AssetPlugin implements Plugin {build(app: App): void {const module = app.wasmModule;if (!module) {- console.warn('AssetPlugin: No WASM module available');+ log.warn('asset', 'AssetPlugin: No WASM module available');return;}diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex d40c9f507..b3a557a98 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -25,6 +25,7 @@ import type { SceneData } from '../scene';import { SceneHandle, type ReleaseCallback } from './SceneHandle';import type { AssetRegistry } from './AssetRegistry';import type { AssetRefCounter } from './AssetRefCounter';+import { log } from '../logger';export interface AssetsOptions {backend: Backend;@@ -300,8 +301,9 @@ export class Assets {missing.push({ ref, reason: 'unresolved' });}if (discovered.unresolved.length > 0) {- console.warn(- `[Assets] ${discovered.unresolved.length} unresolved asset ref(s):`,+ log.warn(+ 'asset',+ `${discovered.unresolved.length} unresolved asset ref(s)`,discovered.unresolved,);}@@ -340,7 +342,7 @@ export class Assets {[...paths].map(path =>trackProgress(loader(path).then(r => { handles.set(path, r.handle); }).catch(e => {- console.warn(`[Assets] Failed to load ${label}: ${path}`, e);+ log.warn('asset', `Failed to load ${label}: ${path}`, e);handles.set(path, 0);recordFailure(path, label, e);}),@@ -353,7 +355,7 @@ export class Assets {[...paths].map(path =>trackProgress(loader(path).then(() => {}).catch(e => {- console.warn(`[Assets] Failed to load ${label}: ${path}`, e);+ log.warn('asset', `Failed to load ${label}: ${path}`, e);recordFailure(path, label, e);}),),@@ -366,7 +368,7 @@ export class Assets {...spinePairs.map(pair =>trackProgress(this.loadSpine(pair.skeleton, pair.atlas).then(() => {}).catch(e => {- console.warn(`[Assets] Failed to load spine: ${pair.skeleton}`, e);+ log.warn('asset', `Failed to load spine: ${pair.skeleton}`, e);recordFailure(pair.skeleton, 'spine', e);}),),diff --git a/sdk/src/asset/AsyncCache.ts b/sdk/src/asset/AsyncCache.tsindex d6523e4c3..7eafee273 100644--- a/sdk/src/asset/AsyncCache.ts+++ b/sdk/src/asset/AsyncCache.ts@@ -1,4 +1,5 @@import { RuntimeConfig } from '../defaults';+import { log } from '../logger';interface PendingEntry<T> {promise: Promise<T>;@@ -65,7 +66,7 @@ export class AsyncCache<T> {if (err instanceof Error) {this.failed_.set(key, { error: err, expiry: Date.now() + RuntimeConfig.assetFailureCooldown });if (err.message.startsWith('AsyncCache timeout:')) {- console.warn(`[AsyncCache] ${err.message}`);+ log.warn('asset', err.message);}}throw err;diff --git a/sdk/src/asset/loaders/AnimClipAssetLoader.ts b/sdk/src/asset/loaders/AnimClipAssetLoader.tsindex 36ad8d12b..3d4dce21b 100644--- a/sdk/src/asset/loaders/AnimClipAssetLoader.ts+++ b/sdk/src/asset/loaders/AnimClipAssetLoader.ts@@ -1,6 +1,7 @@import type { AssetLoader, LoadContext, AnimClipResult } from '../AssetLoader';import { extractAnimClipTexturePaths, parseAnimClipData, type AnimClipAssetData } from '../../animation/AnimClipLoader';import { registerAnimClip } from '../../animation/SpriteAnimator';+import { log } from '../../logger';export class AnimClipAssetLoader implements AssetLoader<AnimClipResult> {readonly type = 'anim-clip';@@ -18,7 +19,7 @@ export class AnimClipAssetLoader implements AssetLoader<AnimClipResult> {const result = await ctx.loadTexture(texPath, true);textureHandles.set(texPath, result.handle);} catch (e) {- console.warn(`[AnimClipLoader] Failed to load texture: ${texPath}`, e);+ log.warn('asset', `Failed to load texture: ${texPath}`, e);textureHandles.set(texPath, 0);}}diff --git a/sdk/src/asset/loaders/SpineAssetLoader.ts b/sdk/src/asset/loaders/SpineAssetLoader.tsindex 5385eb9c3..9efc5c624 100644--- a/sdk/src/asset/loaders/SpineAssetLoader.ts+++ b/sdk/src/asset/loaders/SpineAssetLoader.ts@@ -3,6 +3,7 @@ import { requireResourceManager } from '../../resourceManager';import { getAssetTypeEntry } from '../../assetTypes';import type { ESEngineModule } from '../../wasm';import type { SpineModuleController } from '../../spine/SpineController';+import { log } from '../../logger';export class SpineAssetLoader implements AssetLoader<SpineResult> {readonly type = 'spine';@@ -57,7 +58,7 @@ export class SpineAssetLoader implements AssetLoader<SpineResult> {rm.registerTextureWithPath(texResult.handle, texPath);return { name: texName, handle: texResult.handle, width: texResult.width, height: texResult.height };} catch (err) {- console.warn(`[SpineLoader] Failed to load texture: ${texPath}`, err);+ log.warn('asset', `Failed to load texture: ${texPath}`, err);return null;}});@@ -123,7 +124,7 @@ export class SpineAssetLoader implements AssetLoader<SpineResult> {fs.writeFile(virtualPath, data);this.virtualFSPaths_.add(virtualPath);} catch (e) {- console.warn(`[SpineLoader] Failed to write virtual FS: ${virtualPath}`, e);+ log.warn('asset', `Failed to write virtual FS: ${virtualPath}`, e);}}diff --git a/sdk/src/asset/loaders/TilemapAssetLoader.ts b/sdk/src/asset/loaders/TilemapAssetLoader.tsindex b1403f916..f20f6cb5b 100644--- a/sdk/src/asset/loaders/TilemapAssetLoader.ts+++ b/sdk/src/asset/loaders/TilemapAssetLoader.ts@@ -1,6 +1,7 @@import type { AssetLoader, LoadContext, TilemapResult } from '../AssetLoader';import { parseTmjJson, resolveRelativePath } from '../../tilemap/tiledLoader';import { registerTilemapSource } from '../../tilemap/tilesetCache';+import { log } from '../../logger';export class TilemapAssetLoader implements AssetLoader<TilemapResult> {readonly type = 'tilemap';@@ -22,7 +23,7 @@ export class TilemapAssetLoader implements AssetLoader<TilemapResult> {const result = await ctx.loadTexture(imagePath, true);textureHandle = result.handle;} catch (e) {- console.warn(`[TilemapLoader] Failed to load tileset texture: ${imagePath}`, e);+ log.warn('asset', `Failed to load tileset texture: ${imagePath}`, e);}tilesets.push({ textureHandle, columns: ts.columns });}diff --git a/sdk/src/asset/loaders/TimelineAssetLoader.ts b/sdk/src/asset/loaders/TimelineAssetLoader.tsindex 51d43e294..854b0adca 100644--- a/sdk/src/asset/loaders/TimelineAssetLoader.ts+++ b/sdk/src/asset/loaders/TimelineAssetLoader.ts@@ -1,6 +1,7 @@import type { AssetLoader, LoadContext, TimelineResult } from '../AssetLoader';import { parseTimelineAsset, extractTimelineAssetPaths } from '../../timeline/TimelineLoader';import { registerTimelineAsset, registerTimelineTextureHandles } from '../../timeline/TimelinePlugin';+import { log } from '../../logger';export class TimelineAssetLoader implements AssetLoader<TimelineResult> {readonly type = 'timeline';@@ -19,7 +20,7 @@ export class TimelineAssetLoader implements AssetLoader<TimelineResult> {const result = await ctx.loadTexture(texPath, true);textureHandles.set(texPath, result.handle);} catch (e) {- console.warn(`[TimelineLoader] Failed to load texture: ${texPath}`, e);+ log.warn('asset', `Failed to load texture: ${texPath}`, e);textureHandles.set(texPath, 0);}}diff --git a/sdk/src/audio/Audio.ts b/sdk/src/audio/Audio.tsindex c9d39ed3d..18ada68c7 100644--- a/sdk/src/audio/Audio.ts+++ b/sdk/src/audio/Audio.ts@@ -1,5 +1,6 @@import type { PlatformAudioBackend, AudioBufferHandle, AudioHandle } from './PlatformAudioBackend';import type { AudioMixer } from './AudioMixer';+import { log } from '../logger';export class Audio {private static backend_: PlatformAudioBackend;@@ -81,7 +82,7 @@ export class Audio {pending.resolve(this.backend_.play(buf, playConfig));}}).catch(err => {- console.warn(`Failed to preload audio: ${url}`, err);+ log.warn('audio', `Failed to preload audio: ${url}`, err);});return pending;}@@ -132,7 +133,7 @@ export class Audio {play(buf);}}).catch(err => {- console.warn(`Failed to preload BGM: ${url}`, err);+ log.warn('audio', `Failed to preload BGM: ${url}`, err);});}}diff --git a/sdk/src/audio/AudioPlugin.ts b/sdk/src/audio/AudioPlugin.tsindex 19d8a36f2..1f7eedcce 100644--- a/sdk/src/audio/AudioPlugin.ts+++ b/sdk/src/audio/AudioPlugin.ts@@ -9,6 +9,7 @@ import { getPlatform } from '../platform/base';import { calculateAttenuation, calculatePanning, type SpatialAudioConfig, AttenuationModel } from './SpatialAudio';import type { AudioHandle } from './PlatformAudioBackend';import { isEditor, isPlayMode } from '../env';+import { log } from '../logger';export interface AudioPluginConfig {initialPoolSize?: number;@@ -32,7 +33,7 @@ export class AudioPlugin implements Plugin {const config = this.config_;backend.initialize({ initialPoolSize: config.initialPoolSize }).catch(err => {- console.warn('[AudioPlugin] backend initialization failed:', err);+ log.warn('audio', 'backend initialization failed', err);});const mixer = backend.mixer;@@ -115,8 +116,9 @@ export class AudioPlugin implements Plugin {activeSourceHandles.set(id, handle);playedEntities.add(id);} else {- console.warn(- `[AudioPlugin] playOnAwake: clip "${source.clip}" not preloaded`+ log.warn(+ 'audio',+ `playOnAwake: clip "${source.clip}" not preloaded`,);}}@@ -129,7 +131,7 @@ export class AudioPlugin implements Plugin {}if (!hasListener && !spatialListenerWarned) {- console.warn('[AudioPlugin] spatial audio used but no AudioListener entity found');+ log.warn('audio', 'spatial audio used but no AudioListener entity found');spatialListenerWarned = true;}diff --git a/sdk/src/audio/WeChatAudioBackend.ts b/sdk/src/audio/WeChatAudioBackend.tsindex e00ff88a2..d88d4c4a7 100644--- a/sdk/src/audio/WeChatAudioBackend.ts+++ b/sdk/src/audio/WeChatAudioBackend.ts@@ -1,5 +1,6 @@import type { AudioHandle, AudioBufferHandle, PlayConfig, PlatformAudioBackend, AudioBackendInitOptions } from './PlatformAudioBackend';import type { AudioMixer } from './AudioMixer';+import { log } from '../logger';interface WxInnerAudioContext {src: string;@@ -57,7 +58,7 @@ class WeChatAudioHandle implements AudioHandle {setPan(_pan: number): void {if (!this.panWarned_) {- console.warn('[Audio] WeChat InnerAudioContext does not support stereo panning');+ log.warn('audio', 'WeChat InnerAudioContext does not support stereo panning');this.panWarned_ = true;}}@@ -145,7 +146,7 @@ export class WeChatAudioBackend implements PlatformAudioBackend {}});ctx.onError((res) => {- console.error(`[WeChatAudio] Playback error for "${url}":`, res.errMsg);+ log.error('audio', `Playback error for "${url}"`, res.errMsg);});ctx.src = url;diff --git a/sdk/src/commands.ts b/sdk/src/commands.tsindex df7c7b9d3..a3c5b714f 100644--- a/sdk/src/commands.ts+++ b/sdk/src/commands.ts@@ -7,6 +7,7 @@ import { Entity } from './types';import { AnyComponentDef, ComponentDef, isBuiltinComponent, Name } from './component';import type { World } from './world';import { ResourceDef, ResourceStorage } from './resource';+import { log } from './logger';// =============================================================================// Commands Descriptor (for system parameters)@@ -189,7 +190,7 @@ export class CommandsInstance {try {this.executeCommand(cmd);} catch (e) {- console.warn('[Commands] Failed to execute command:', cmd.type, e);+ log.warn('commands', `Failed to execute command: ${cmd.type}`, e);}}this.pending_.length = 0;@@ -199,7 +200,7 @@ export class CommandsInstance {switch (cmd.type) {case 'despawn':if (!this.world_.valid(cmd.entity)) {- console.warn(`[Commands] despawn skipped: entity ${cmd.entity} is already invalid`);+ log.warn('commands', `despawn skipped: entity ${cmd.entity} is already invalid`);break;}this.world_.despawn(cmd.entity);@@ -207,7 +208,7 @@ export class CommandsInstance {case 'insert':if (!this.world_.valid(cmd.entity)) {- console.warn(`[Commands] insert skipped: entity ${cmd.entity} is invalid`);+ log.warn('commands', `insert skipped: entity ${cmd.entity} is invalid`);break;}this.world_.insert(cmd.entity, cmd.component, cmd.data as Record<string, unknown>);@@ -215,7 +216,7 @@ export class CommandsInstance {case 'remove':if (!this.world_.valid(cmd.entity)) {- console.warn(`[Commands] remove skipped: entity ${cmd.entity} is invalid`);+ log.warn('commands', `remove skipped: entity ${cmd.entity} is invalid`);break;}this.world_.remove(cmd.entity, cmd.component);diff --git a/sdk/src/core.ts b/sdk/src/core.tsindex f5f5f5fd7..4bc603494 100644--- a/sdk/src/core.ts+++ b/sdk/src/core.ts@@ -726,6 +726,7 @@ export type {export {Logger,getLogger,+ log,setLogLevel,debug,info,diff --git a/sdk/src/draw.ts b/sdk/src/draw.tsindex 0ee4a28e0..74de9155e 100644--- a/sdk/src/draw.ts+++ b/sdk/src/draw.ts@@ -12,6 +12,7 @@ import type { ShaderHandle, MaterialHandle } from './material';import { Material, isTextureRef } from './material';import { BlendMode } from './blend';import { handleWasmError } from './wasmError';+import { log } from './logger';export { BlendMode } from './blend';@@ -376,7 +377,7 @@ export const Draw: DrawAPI = {let autoTextureSlot = 0;for (const [name, value] of matData.uniforms) {if (idx > UNIFORMS_BUFFER_SIZE - 6) {- console.warn('Uniform buffer overflow, some uniforms will be ignored');+ log.warn('draw', 'Uniform buffer overflow, some uniforms will be ignored');break;}@@ -469,9 +470,9 @@ function getUniformNameId(name: string): number {if (id !== undefined) return id;if (!warnedUniforms.has(name)) {warnedUniforms.add(name);- console.warn(- `[ESEngine] Unknown uniform name "${name}" - ` +- `supported names: ${Object.keys(UNIFORM_NAME_MAP).join(', ')}`+ log.warn(+ 'draw',+ `Unknown uniform name "${name}" - supported: ${Object.keys(UNIFORM_NAME_MAP).join(', ')}`,);}return -1;diff --git a/sdk/src/ecs/ScriptStorage.ts b/sdk/src/ecs/ScriptStorage.tsindex fb3c06699..e65b66492 100644--- a/sdk/src/ecs/ScriptStorage.ts+++ b/sdk/src/ecs/ScriptStorage.ts@@ -6,6 +6,7 @@import { Entity } from '../types';import { ComponentDef } from '../component';import { validateComponentData, formatValidationErrors } from '../validation';+import { log } from '../logger';export interface InsertResult<T> {value: T;@@ -79,7 +80,7 @@ export class ScriptStorage {data as Record<string, unknown>,);if (errors.length > 0) {- console.warn(formatValidationErrors(component._name, errors));+ log.warn('ecs', formatValidationErrors(component._name, errors));}}this.getStorage(component).set(entity, data);diff --git a/sdk/src/lifecycle.ts b/sdk/src/lifecycle.tsindex 3a7b7c0ac..a0356f7ef 100644--- a/sdk/src/lifecycle.ts+++ b/sdk/src/lifecycle.ts@@ -6,6 +6,7 @@import { defineResource } from './resource';import type { Plugin } from './app';import { getPlatformType } from './platform';+import { log } from './logger';// =============================================================================// Lifecycle State@@ -70,7 +71,7 @@ export class LifecycleManager {emit_(event: LifecycleEvent): void {for (const listener of this.listeners_) {try { listener(event); } catch (e) {- console.error('[Lifecycle] Listener error:', e);+ log.error('lifecycle', 'Listener error', e);}}}diff --git a/sdk/src/logger.ts b/sdk/src/logger.tsindex d62a5e874..ab0ffb79f 100644--- a/sdk/src/logger.ts+++ b/sdk/src/logger.ts@@ -26,24 +26,42 @@ class ConsoleLogHandler implements LogHandler {handle(entry: LogEntry): void {const time = new Date(entry.timestamp).toISOString().substring(11, 23);const levelStr = LogLevel[entry.level].toUpperCase().padEnd(5);- const prefix = `[${time}] [${levelStr}] [${entry.category}]`;- const message = entry.data !== undefined- ? `${entry.message} ${JSON.stringify(entry.data)}`- : entry.message;+ // One formatted string as the first arg so existing console-based+ // test spies (and simple substring checks) see the whole message.+ // Error instances go through as a separate second arg so the+ // console can render their stack trace natively — JSON.stringify+ // on an Error loses the stack, and on cyclic structures throws.+ let line = `[${time}] [${levelStr}] [${entry.category}] ${entry.message}`;+ let errorArg: Error | undefined;++ if (entry.data !== undefined) {+ if (entry.data instanceof Error) {+ errorArg = entry.data;+ } else {+ try {+ line += ` ${JSON.stringify(entry.data)}`;+ } catch {+ line += ` ${String(entry.data)}`;+ }+ }+ }++ const args: unknown[] = [line];+ if (errorArg) args.push(errorArg);switch (entry.level) {case LogLevel.Debug:- console.debug(prefix, message);+ console.debug(...args);break;case LogLevel.Info:- console.log(prefix, message);+ console.log(...args);break;case LogLevel.Warn:- console.warn(prefix, message);+ console.warn(...args);break;case LogLevel.Error:- console.error(prefix, message);+ console.error(...args);break;}}@@ -117,6 +135,15 @@ export class Logger {const defaultLogger = new Logger();+/**+ * Default logger singleton. Prefer this over `console.*` inside the SDK+ * so consumers can install a handler (e.g. an editor log panel) and+ * receive structured `LogEntry`s with category + level.+ *+ * Usage: `import { log } from './logger'; log.warn('physics', 'foo', err);`+ */+export const log = defaultLogger;+export function getLogger(): Logger {return defaultLogger;}diff --git a/sdk/src/material.ts b/sdk/src/material.tsindex e474d1669..028655dcc 100644--- a/sdk/src/material.ts+++ b/sdk/src/material.ts@@ -8,6 +8,7 @@ import type { ESEngineModule } from './wasm';import { requireResourceManager } from './resourceManager';import type { Vec2, Vec3, Vec4 } from './types';import { BlendMode } from './blend';+import { log } from './logger';export type { Vec2, Vec3, Vec4 } from './types';@@ -383,7 +384,7 @@ function serializeUniforms(uniforms: Map<string, UniformValue>): { ptr: number;const requiredBytes = 4 + namePadded + 4 + 16;if (offset + requiredBytes > UNIFORM_BUFFER_SIZE) {- console.warn(`[ESEngine] Material uniform buffer full (${offset}/${UNIFORM_BUFFER_SIZE} bytes), skipping remaining uniforms`);+ log.warn('material', `uniform buffer full (${offset}/${UNIFORM_BUFFER_SIZE} bytes), skipping remaining uniforms`);break;}diff --git a/sdk/src/platform/wechat/index.ts b/sdk/src/platform/wechat/index.tsindex 67cbc36cb..21e29a273 100644--- a/sdk/src/platform/wechat/index.ts+++ b/sdk/src/platform/wechat/index.ts@@ -20,6 +20,7 @@ import { wxInstantiateWasm, polyfillWebAssembly } from './wasm';import { wxReadFileSync, wxReadTextFileSync, wxFileExistsSync } from './fs';import { wxLoadImagePixels } from './image';import { toBuildPath } from '../../assetTypes';+import { log } from '../../logger';// =============================================================================// WeChat Platform Adapter@@ -162,7 +163,7 @@ class WeChatPlatformAdapter implements PlatformAdapter {try {wx.setStorageSync(key, value);} catch (e) {- console.warn('[WeChat] setStorageSync failed:', e);+ log.warn('wechat', 'setStorageSync failed', e);}}@@ -170,7 +171,7 @@ class WeChatPlatformAdapter implements PlatformAdapter {try {wx.removeStorageSync(key);} catch (e) {- console.warn('[WeChat] removeStorageSync failed:', e);+ log.warn('wechat', 'removeStorageSync failed', e);}}@@ -191,7 +192,7 @@ class WeChatPlatformAdapter implements PlatformAdapter {}}} catch (e) {- console.warn('[WeChat] clearStorage failed:', e);+ log.warn('wechat', 'clearStorage failed', e);}}}@@ -215,7 +216,7 @@ export function initWeChatPlatform(): void {polyfillWebAssembly();polyfillTextEncoder();- console.log('[ESEngine] WeChat platform initialized');+ log.info('wechat', 'WeChat platform initialized');}function polyfillPerformance(): void {diff --git a/sdk/src/playableRuntime.ts b/sdk/src/playableRuntime.tsindex 94a888de1..4a03173ef 100644--- a/sdk/src/playableRuntime.ts+++ b/sdk/src/playableRuntime.ts@@ -16,6 +16,7 @@ import { SpinePlugin } from './spine/SpinePlugin';import type { PhysicsWasmModule } from './physics/PhysicsModuleLoader';import type { SceneData } from './scene';import { Audio } from './audio/Audio';+import { log } from './logger';declare const ESPhysicsModule: ((opts: unknown) => Promise<PhysicsWasmModule>) | undefined;@@ -127,7 +128,7 @@ async function instantiateWasmModule(r => cb((r as WebAssembly.WebAssemblyInstantiatedSource).instance,(r as WebAssembly.WebAssemblyInstantiatedSource).module),).catch(e => {- console.error('[Playable] WASM instantiation fallback failed:', e);+ log.error('playable', 'WASM instantiation fallback failed', e);});},);@@ -136,7 +137,7 @@ async function instantiateWasmModule(};return await factory(opts);} catch (e) {- console.error('[Playable] WASM module init failed:', e);+ log.error('playable', 'WASM module init failed', e);return null;}}@@ -144,7 +145,7 @@ async function instantiateWasmModule(async function initPhysicsModule(wasmBase64: string): Promise<PhysicsWasmModule | null> {if (typeof ESPhysicsModule === 'undefined') return null;const mod = await instantiateWasmModule(ESPhysicsModule, wasmBase64);- if (!mod) console.warn('Physics module not available');+ if (!mod) log.warn('playable', 'Physics module not available');return mod as PhysicsWasmModule | null;}@@ -169,7 +170,7 @@ function buildSpineManager(r => cb((r as WebAssembly.WebAssemblyInstantiatedSource).instance,(r as WebAssembly.WebAssemblyInstantiatedSource).module),).catch(e => {- console.error('[Playable] Spine WASM instantiation fallback failed:', e);+ log.error('playable', 'Spine WASM instantiation fallback failed', e);});},);diff --git a/sdk/src/preview/PreviewPlugin.ts b/sdk/src/preview/PreviewPlugin.tsindex 80d4bbb05..4a253885a 100644--- a/sdk/src/preview/PreviewPlugin.ts+++ b/sdk/src/preview/PreviewPlugin.ts@@ -12,6 +12,7 @@ import { platformFetch } from '../platform';import { SceneManager } from '../sceneManager';import { WebAssetProvider } from './WebAssetProvider';import { SpinePlugin } from '../spine/SpinePlugin';+import { log } from '../logger';const PREVIEW_SCENE = '__preview__';@@ -48,7 +49,7 @@ export class PreviewPlugin implements Plugin {manager.setInitial(PREVIEW_SCENE);this.loadPromise_ = manager.load(PREVIEW_SCENE).then(() => {}).catch(e => {- console.error('[Preview] Failed to load preview scene:', e);+ log.error('preview', 'Failed to load preview scene', e);});this.setupHotReload();}@@ -103,7 +104,7 @@ export class PreviewPlugin implements Plugin {}if (!hasActiveCamera) {- console.warn('[PreviewPlugin] No active camera found, creating default camera');+ log.warn('preview', 'No active camera found, creating default camera');let orthoSize = 540;let aspectRatio = DEFAULT_DESIGN_WIDTH / DEFAULT_DESIGN_HEIGHT;@@ -177,13 +178,13 @@ export class PreviewPlugin implements Plugin {this.onMessage_ = async (event: MessageEvent) => {if (event.data === 'reload') {- console.log('[PreviewPlugin] Reload event received, updating scene...');+ log.info('preview', 'Reload event received, updating scene...');await this.reloadScene();}};this.onError_ = (err: Event) => {- console.error('[PreviewPlugin] EventSource error:', err);+ log.error('preview', 'EventSource error', err);};this.eventSource_.addEventListener('message', this.onMessage_ as EventListener);@@ -196,10 +197,10 @@ export class PreviewPlugin implements Plugin {try {const manager = this.app_.getResource(SceneManager);await manager.switchTo(PREVIEW_SCENE);- console.log('[PreviewPlugin] Scene reloaded successfully');+ log.info('preview', 'Scene reloaded successfully');} catch (err) {const msg = err instanceof Error ? err.message : String(err);- console.error(`[PreviewPlugin] Failed to reload scene: ${msg}`);+ log.error('preview', `Failed to reload scene: ${msg}`);}}}diff --git a/sdk/src/preview/WebAssetProvider.ts b/sdk/src/preview/WebAssetProvider.tsindex 63ece93ec..4a34e05b5 100644--- a/sdk/src/preview/WebAssetProvider.ts+++ b/sdk/src/preview/WebAssetProvider.ts@@ -7,6 +7,7 @@ import type { RuntimeAssetProvider } from '../runtimeLoader';import type { SceneData } from '../scene';import { getComponentAssetFieldDescriptors, getComponentSpineFieldDescriptor } from '../scene';import { getAssetTypeEntry } from '../assetTypes';+import { log } from '../logger';export class WebAssetProvider implements RuntimeAssetProvider {private textCache_ = new Map<string, string>();@@ -65,7 +66,7 @@ export class WebAssetProvider implements RuntimeAssetProvider {fetch(this.resolveUrl(ref)).then(r => r.text()).then(text => { this.textCache_.set(ref, text); })- .catch(err => { console.warn(`[WebAssetProvider] Failed to prefetch text "${ref}":`, err); })+ .catch(err => { log.warn('preview', `Failed to prefetch text "${ref}"`, err); }));}@@ -74,7 +75,7 @@ export class WebAssetProvider implements RuntimeAssetProvider {fetch(this.resolveUrl(ref)).then(r => r.arrayBuffer()).then(buf => { this.binaryCache_.set(ref, new Uint8Array(buf)); })- .catch(err => { console.warn(`[WebAssetProvider] Failed to prefetch binary "${ref}":`, err); })+ .catch(err => { log.warn('preview', `Failed to prefetch binary "${ref}"`, err); }));}@@ -97,7 +98,7 @@ export class WebAssetProvider implements RuntimeAssetProvider {fetch(this.resolveUrl(fntRef)).then(r => r.text()).then(t => { this.textCache_.set(fntRef, t); })- .catch(err => { console.warn(`[WebAssetProvider] Failed to prefetch font "${fntRef}":`, err); })+ .catch(err => { log.warn('preview', `Failed to prefetch font "${fntRef}"`, err); }));}}diff --git a/sdk/src/renderPipeline.ts b/sdk/src/renderPipeline.tsindex ab8b634c7..d9426086a 100644--- a/sdk/src/renderPipeline.ts+++ b/sdk/src/renderPipeline.ts@@ -9,6 +9,7 @@ import { Renderer } from './renderer';import { PostProcess } from './postprocess';import { Draw } from './draw';import { getDrawCallbacks, unregisterDrawCallback } from './customDraw';+import { log } from './logger';export interface Viewport {x: number;@@ -137,7 +138,7 @@ export class RenderPipeline {try {entry.fn(elapsed);} catch (e) {- console.error(`[CustomDraw] callback '${id}' error:`, e);+ log.error('render', `callback '${id}' error`, e);failed.push(id);}}diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex 7280278ce..873ccbab7 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -27,6 +27,7 @@ import { updateCameraAspectRatio } from './scene';import { requireResourceManager } from './resourceManager';import { parseTmjJson, resolveRelativePath } from './tilemap/tiledLoader';import { registerTilemapSource } from './tilemap/tilesetCache';+import { log } from './logger';// =============================================================================// Public Interface@@ -89,7 +90,7 @@ async function loadTextures(const handle = createTextureFromPixels(module, pixelData, true, params);cache[ref] = handle;} catch (e) {- console.warn(`[loadTextures] Failed to load texture: ${ref}`, e);+ log.warn('runtime', `Failed to load texture: ${ref}`, e);cache[ref] = 0;}}@@ -177,7 +178,7 @@ function writeToVirtualFS(module: ESEngineModule, virtualPath: string, data: strfs.writeFile(virtualPath, data);return true;} catch (e) {- console.warn(`[Runtime] Failed to write virtual FS: ${virtualPath}`, e);+ log.warn('runtime', `Failed to write virtual FS: ${virtualPath}`, e);return false;}}@@ -238,7 +239,7 @@ async function loadSpineAssetsToVirtualFS(h: result.height,});} catch (err) {- console.warn(`[Spine] Failed to load texture: ${texPath}`, err);+ log.warn('runtime', `Failed to load texture: ${texPath}`, err);}}@@ -250,7 +251,7 @@ async function loadSpineAssetsToVirtualFS(assetInfoMap.set(cacheKey, { version, skelData, atlasText: atlasContent, textures });} catch (err) {- console.warn(`[Runtime] Failed to load spine asset: skel=${skelRef} atlas=${atlasRef}`, err);+ log.warn('runtime', `Failed to load spine asset: skel=${skelRef} atlas=${atlasRef}`, err);}}return assetInfoMap;@@ -298,7 +299,7 @@ async function loadBitmapFonts(const rm = requireResourceManager();cache[ref] = rm.loadBitmapFont(fntContent, texHandle, pixels.width, pixels.height);} catch (e) {- console.warn(`[Runtime] Failed to load bitmap font: ${ref}`, e);+ log.warn('runtime', `Failed to load bitmap font: ${ref}`, e);cache[ref] = 0;}}@@ -331,7 +332,7 @@ async function loadMaterials(}materialCache[matRef] = Material.createFromAsset(matData, shaderHandle);} catch (e) {- console.warn(`[Runtime] Failed to load material: ${matRef}`, e);+ log.warn('runtime', `Failed to load material: ${matRef}`, e);materialCache[matRef] = 0;}}@@ -353,12 +354,12 @@ async function preloadAudioClips(provider: RuntimeAssetProvider, audioPaths: Setconst binary = await provider.readBinary(path);await Audio.preloadFromData(path, binary.buffer as ArrayBuffer);} catch (err) {- console.warn(`[preloadAudioClips] Failed to preload audio: ${path}`, err);+ log.warn('runtime', `Failed to preload audio: ${path}`, err);}}));} else {await Audio.preloadAll(paths).catch(err => {- console.warn('[preloadAudioClips] Failed to preload audio assets:', err);+ log.warn('runtime', 'Failed to preload audio assets', err);});}}@@ -384,7 +385,7 @@ async function loadAnimClips(const result = await provider.loadPixels(texPath);textureHandles.set(texPath, createTextureFromPixels(module, result));} catch (e) {- console.warn(`[Runtime] Failed to load anim texture: ${texPath}`, e);+ log.warn('runtime', `Failed to load anim texture: ${texPath}`, e);textureHandles.set(texPath, 0);}}@@ -392,7 +393,7 @@ async function loadAnimClips(const clip = parseAnimClipData(clipPath, clipData, textureHandles);registerAnimClip(clip);} catch (err) {- console.warn(`[loadAnimClips] Failed to load animation clip: ${clipPath}`, err);+ log.warn('runtime', `Failed to load animation clip: ${clipPath}`, err);}}}@@ -420,7 +421,7 @@ async function loadTilemaps(const result = await provider.loadPixels(imagePath);textureHandle = createTextureFromPixels(module, result);} catch (e) {- console.warn(`[Runtime] Failed to load tileset texture: ${imagePath}`, e);+ log.warn('runtime', `Failed to load tileset texture: ${imagePath}`, e);}tilesets.push({ textureHandle, columns: ts.columns });}@@ -439,7 +440,7 @@ async function loadTilemaps(tilesets,});} catch (err) {- console.warn(`[loadTilemaps] Failed to load tilemap: ${tmjPath}`, err);+ log.warn('runtime', `Failed to load tilemap: ${tmjPath}`, err);}}}diff --git a/sdk/src/scene.ts b/sdk/src/scene.tsindex a447666b7..36d508a6e 100644--- a/sdk/src/scene.ts+++ b/sdk/src/scene.ts@@ -9,6 +9,7 @@ import { getComponent, Name, Camera } from './component';import { discoverSceneAssets } from './asset/discoverAssets';import { requireResourceManager } from './resourceManager';import { validateComponentData, formatValidationErrors } from './validation';+import { log } from './logger';// =============================================================================// Types@@ -136,8 +137,9 @@ export function remapEntityFields(compData: SceneComponentData, entityMap: Map<nif (typeof editorId === 'number' && editorId !== INVALID_ENTITY) {const runtimeId = entityMap.get(editorId);if (runtimeId === undefined) {- console.warn(- `[Scene] Entity reference not found: ${compData.type}.${field} ` ++ log.warn(+ 'scene',+ `Entity reference not found: ${compData.type}.${field} ` +`references entity ${editorId} which does not exist`,);}@@ -282,12 +284,12 @@ export function loadComponent(world: World, entity: Entity, compData: SceneCompoconst errors = validateComponentData(compData.type, comp._default as Record<string, unknown>, compData.data);if (errors.length > 0) {const context = entityName ? ` (entity "${entityName}")` : '';- console.warn(formatValidationErrors(compData.type + context, errors));+ log.warn('scene', formatValidationErrors(compData.type + context, errors));}world.insert(entity, comp, compData.data);} else {const context = entityName ? ` on entity "${entityName}"` : '';- console.warn(`Unknown component type: ${compData.type}${context}`);+ log.warn('scene', `Unknown component type: ${compData.type}${context}`);}}diff --git a/sdk/src/sceneManager.ts b/sdk/src/sceneManager.tsindex 46fee7fbc..06ade6aa3 100644--- a/sdk/src/sceneManager.ts+++ b/sdk/src/sceneManager.ts@@ -24,6 +24,7 @@ import {import { UIRenderer } from './ui/core/ui-renderer';import { Assets } from './asset/AssetPlugin';import { RuntimeConfig } from './defaults';+import { log } from './logger';const RENDERABLE_COMPONENTS: AnyComponentDef[] = [Sprite, SpineAnimation, BitmapText, ShapeRenderer, ParticleEmitter, UIRenderer,@@ -229,7 +230,7 @@ export class SceneManagerState {async switchTo(name: string, options?: TransitionOptions): Promise<void> {if (this.transition_ || this.switching_) {- console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${name}")`);+ log.warn('scene', `Scene switch already in progress, ignoring switchTo("${name}")`);return;}@@ -305,7 +306,7 @@ export class SceneManagerState {}await this.load(targetScene);} catch (err) {- console.error('Scene transition failed:', err);+ log.error('scene', 'Scene transition failed', err);const { reject: rejectTransition } = this.transition_!;this.transition_ = null;unregisterDrawCallback(TRANSITION_CALLBACK_ID);diff --git a/sdk/src/scenePlugin.ts b/sdk/src/scenePlugin.tsindex fa999f252..ed0f66a91 100644--- a/sdk/src/scenePlugin.ts+++ b/sdk/src/scenePlugin.ts@@ -8,6 +8,7 @@ import { SceneManager, SceneManagerState } from './sceneManager';import { defineSystem, Schedule } from './system';import { Res, ResMut, Time } from './resource';import type { SystemDef } from './system';+import { log } from './logger';const sceneTransitionSystem = defineSystem([ResMut(SceneManager), Res(Time)],@@ -33,7 +34,7 @@ export const sceneManagerPlugin: Plugin = {const initial = manager.getInitial();if (initial) {manager.load(initial).catch(err => {- console.error('Failed to load initial scene:', err);+ log.error('scene', 'Failed to load initial scene', err);});}},diff --git a/sdk/src/spine/ModuleBackend.ts b/sdk/src/spine/ModuleBackend.tsindex 7e52d3a0e..1d0b6edb3 100644--- a/sdk/src/spine/ModuleBackend.ts+++ b/sdk/src/spine/ModuleBackend.ts@@ -2,6 +2,7 @@ import type { Entity } from '../types';import type { ESEngineModule, CppRegistry } from '../wasm';import type { SpineModuleController } from './SpineController';import type { RawSpineEvent, ConstraintList, TransformMixData, PathMixData } from './SpineController';+import { log } from '../logger';interface EntityInfo {skelHandle: number;@@ -46,7 +47,7 @@ export class ModuleBackend {): boolean {const skelHandle = this.controller_.loadSkeleton(skelData, atlasText, isBinary);if (skelHandle < 0) {- console.error(`[ModuleBackend] Failed to load skeleton: ${this.controller_.getLastError()}`);+ log.error('spine', `Failed to load skeleton: ${this.controller_.getLastError()}`);return false;}diff --git a/sdk/src/spine/SpineController.ts b/sdk/src/spine/SpineController.tsindex 42b4c38ae..a9e52b30f 100644--- a/sdk/src/spine/SpineController.ts+++ b/sdk/src/spine/SpineController.ts@@ -5,6 +5,7 @@import type { Entity, Vec2 } from '../types';import type { SpineWasmModule, SpineWrappedAPI } from './SpineModuleLoader';+import { log } from '../logger';export type SpineEventType = 'start' | 'interrupt' | 'end' | 'complete' | 'dispose' | 'event';@@ -157,7 +158,7 @@ export class SpineModuleController {try {return JSON.parse(json);} catch (e) {- console.warn('[Spine] Failed to parse animations JSON', e);+ log.warn('spine', 'Failed to parse animations JSON', e);return [];}}@@ -167,7 +168,7 @@ export class SpineModuleController {try {return JSON.parse(json);} catch (e) {- console.warn('[Spine] Failed to parse skins JSON', e);+ log.warn('spine', 'Failed to parse skins JSON', e);return [];}}diff --git a/sdk/src/spine/SpineManager.ts b/sdk/src/spine/SpineManager.tsindex 85621562c..532e79c0f 100644--- a/sdk/src/spine/SpineManager.ts+++ b/sdk/src/spine/SpineManager.ts@@ -6,6 +6,7 @@ import { wrapSpineModule } from './SpineModuleLoader';import { SpineModuleController } from './SpineController';import { ModuleBackend } from './ModuleBackend';import { SpineCpp } from './SpineCppAPI';+import { log } from '../logger';export type SpineVersion = '3.8' | '4.1' | '4.2';@@ -70,14 +71,14 @@ export class SpineManager {const backend = await this.ensureBackend(version);if (!backend) {- console.error(`[SpineManager] Failed to create backend for version ${version}`);+ log.error('spine', `Failed to create backend for version ${version}`);return null;}const isBinary = skelData instanceof Uint8Array;const ok = backend.loadEntity(entity, skelData, atlasText, textures, isBinary);if (!ok) {- console.error(`[SpineManager] Failed to load entity ${entity} into backend ${version}`);+ log.error('spine', `Failed to load entity ${entity} into backend ${version}`);return null;}this.entityVersions_.set(entity, version);@@ -282,7 +283,7 @@ export class SpineManager {const factory = this.factories_.get(version);if (!factory) {- console.warn(`[SpineManager] No module factory for version ${version}`);+ log.warn('spine', `No module factory for version ${version}`);return null;}@@ -295,7 +296,7 @@ export class SpineManager {this.backends_.set(version, backend);return backend;} catch (e) {- console.error(`[SpineManager] Failed to load WASM module for version ${version}:`, e);+ log.error('spine', `Failed to load WASM module for version ${version}`, e);return null;} finally {this.loadingBackends_.delete(version);diff --git a/sdk/src/spine/SpineModuleLoader.ts b/sdk/src/spine/SpineModuleLoader.tsindex ab6e5a67d..3c96e237f 100644--- a/sdk/src/spine/SpineModuleLoader.ts+++ b/sdk/src/spine/SpineModuleLoader.ts@@ -3,6 +3,8 @@* @brief Loads and initializes the standalone Spine WASM module*/+import { log } from '../logger';+export interface SpineWasmModule {_spine_loadSkeleton(skelDataPtr: number, skelDataLen: number, atlasText: number, atlasLen: number, isBinary: number): number;_spine_unloadSkeleton(handle: number): void;@@ -189,7 +191,7 @@ export function createSpineFactories(provider: SpineWasmProvider): Map<SpineVersWebAssembly.instantiate(wasmBytes, imports).then(r => cb(r.instance, r.module),).catch(e => {- console.error('[Spine] WASM instantiation failed:', e);+ log.error('spine', 'WASM instantiation failed', e);});return {};},diff --git a/sdk/src/storage.ts b/sdk/src/storage.tsindex 3fe1f0112..a5857ffce 100644--- a/sdk/src/storage.ts+++ b/sdk/src/storage.ts@@ -1,4 +1,5 @@import { getPlatform } from './platform/base';+import { log } from './logger';const KEY_PREFIX = 'esengine:';@@ -39,7 +40,7 @@ export const Storage = {try {return JSON.parse(raw) as T;} catch (e) {- console.warn(`[Storage] Failed to parse JSON for key "${key}"`, e);+ log.warn('storage', `Failed to parse JSON for key "${key}"`, e);return defaultValue;}},diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.tsindex 2097cca83..aae64d992 100644--- a/sdk/src/tilemap/tiledLoader.ts+++ b/sdk/src/tilemap/tiledLoader.ts@@ -5,6 +5,7 @@ import { TilemapLayer } from './components';import { Transform } from '../component';import { RigidBody, BoxCollider, CircleCollider, BodyType } from '../physics/PhysicsComponents';import { mergeCollisionTiles } from './collisionMerge';+import { log } from '../logger';export interface TiledChunkData {x: number;@@ -428,7 +429,7 @@ export async function parseTiledMap(api.tiled_freeMap(handle);return result;} catch (e) {- console.warn('[Tiled] Failed to parse tilemap', e);+ log.warn('tilemap', 'Failed to parse tilemap', e);api.tiled_freeMap(handle);return null;}diff --git a/sdk/src/timeline/TimelineLoader.ts b/sdk/src/timeline/TimelineLoader.tsindex 5e5314a52..09da2c10f 100644--- a/sdk/src/timeline/TimelineLoader.ts+++ b/sdk/src/timeline/TimelineLoader.ts@@ -12,6 +12,7 @@ import {type CustomEventTrack,type AnimFramesTrack,} from './TimelineTypes';+import { log } from '../logger';const CURRENT_VERSION = '1.1';@@ -138,7 +139,7 @@ function parseTrack(raw: any): Track {} as AnimFramesTrack;default:- console.warn(`[Timeline] Unknown track type: ${raw.type}, skipping`);+ log.warn('timeline', `Unknown track type: ${raw.type}, skipping`);return null as any;}}diff --git a/sdk/src/ui/TextInputPlugin.ts b/sdk/src/ui/TextInputPlugin.tsindex 8648f7751..8a29ab49f 100644--- a/sdk/src/ui/TextInputPlugin.ts+++ b/sdk/src/ui/TextInputPlugin.ts@@ -18,6 +18,7 @@ import { playModeOnly } from '../env';import { wrapText, nextPowerOf2, ensureComponent, colorToRgba } from './uiHelpers';import { CURSOR_BLINK_INTERVAL, TEXT_INPUT_LINE_HEIGHT_RATIO } from './uiConstants';import { SystemLabel, PluginName } from '../systemLabels';+import { log } from '../logger';export class TextInputPlugin implements Plugin {name = PluginName.TextInput;@@ -39,7 +40,7 @@ export class TextInputPlugin implements Plugin {const moduleOrNull = app.wasmModule;if (!moduleOrNull) {- console.warn('TextInputPlugin: No WASM module available');+ log.warn('ui', 'TextInputPlugin: No WASM module available');return;}const module = moduleOrNull;@@ -49,7 +50,7 @@ export class TextInputPlugin implements Plugin {const canvas = platformCreateCanvas(RuntimeConfig.textCanvasSize, 64);const ctxOrNull = canvas.getContext('2d', { willReadFrequently: true });if (!ctxOrNull) {- console.warn('TextInputPlugin: failed to create 2D canvas context');+ log.warn('ui', 'TextInputPlugin: failed to create 2D canvas context');return;}const ctx = ctxOrNull as CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;diff --git a/sdk/src/ui/TextPlugin.ts b/sdk/src/ui/TextPlugin.tsindex 0707a6b23..eefbd637c 100644--- a/sdk/src/ui/TextPlugin.ts+++ b/sdk/src/ui/TextPlugin.ts@@ -11,6 +11,7 @@ import { getEffectiveWidth, getEffectiveHeight, setUIRectSizeNative, ensureUIRenimport { getImageResolver, type DefaultImageResolver } from './ImageResolver';import { parseRichText } from './RichTextParser';import { SystemLabel, PluginName } from '../systemLabels';+import { log } from '../logger';export class TextPlugin implements Plugin {name = PluginName.Text;@@ -21,7 +22,7 @@ export class TextPlugin implements Plugin {const module = app.wasmModule;if (!module) {- console.warn('TextPlugin: No WASM module available');+ log.warn('ui', 'TextPlugin: No WASM module available');return;}diff --git a/sdk/src/ui/TextRenderer.ts b/sdk/src/ui/TextRenderer.tsindex 245ece993..9fd6f95df 100644--- a/sdk/src/ui/TextRenderer.ts+++ b/sdk/src/ui/TextRenderer.ts@@ -14,6 +14,7 @@ import { TEXT_PADDING_RATIO, TEXT_CANVAS_SHRINK_FRAMES, TEXT_CANVAS_OVERSIZE_RATimport { parseRichText } from './RichTextParser';import { createFontSet, fontIndex, layoutRichText, measureLayoutWidth, type LayoutLine } from './RichTextLayout';import type { ImageResolver } from './ImageResolver';+import { log } from '../logger';interface SizedRect {size: { x: number; y: number };@@ -86,7 +87,7 @@ export class TextRenderer {try {return this.renderTextInner(text, uiRect);} catch (e) {- console.error('TextRenderer: render failed', e);+ log.error('ui', 'TextRenderer: render failed', e);return { textureHandle: 0, width: 0, height: 0 };}}diff --git a/sdk/src/ui/collection/data-source.ts b/sdk/src/ui/collection/data-source.tsindex 9e92f8019..746238d63 100644--- a/sdk/src/ui/collection/data-source.ts+++ b/sdk/src/ui/collection/data-source.ts@@ -1,3 +1,5 @@+import { log } from '../../logger';+/*** Change notification emitted by a DataSource.*/@@ -98,7 +100,7 @@ export class ArrayDataSource<T> implements DataSource<T> {try {listener(change);} catch (err) {- console.error('[ArrayDataSource] listener error:', err);+ log.error('ui', 'ArrayDataSource listener error', err);}}}diff --git a/sdk/src/ui/collection/list-view.ts b/sdk/src/ui/collection/list-view.tsindex 7d1edb555..9e012082c 100644--- a/sdk/src/ui/collection/list-view.ts+++ b/sdk/src/ui/collection/list-view.ts@@ -5,6 +5,7 @@ import type { World } from '../../world';import type { DataSource } from './data-source';import type { LayoutProvider, Rect } from './layout-provider';import { ViewPool, type ViewPoolTemplate } from './view-pool';+import { log } from '../../logger';export interface ListViewItemTemplate<T = unknown> extends ViewPoolTemplate<T> {}@@ -181,7 +182,7 @@ export class ListView<T = unknown> {entity = existing.entity;} else {if (!this.pool_.hasTemplate(itemType)) {- console.warn(`[ListView] No template for item type "${itemType}" at index ${i}`);+ log.warn('ui', `ListView: No template for item type "${itemType}" at index ${i}`);continue;}entity = this.pool_.acquire(itemType, this.parent_);diff --git a/sdk/src/ui/collection/scroll-container.ts b/sdk/src/ui/collection/scroll-container.tsindex bc2ed4990..bd9c8c698 100644--- a/sdk/src/ui/collection/scroll-container.ts+++ b/sdk/src/ui/collection/scroll-container.ts@@ -1,4 +1,5 @@import type { Vec2 } from '../../types';+import { log } from '../../logger';export interface ScrollContainerOptions {viewportSize: Vec2;@@ -73,7 +74,7 @@ export class ScrollContainer {try {listener({ x: next.x, y: next.y });} catch (err) {- console.error('[ScrollContainer] listener error:', err);+ log.error('ui', 'ScrollContainer listener error', err);}}}diff --git a/sdk/src/ui/core/events.ts b/sdk/src/ui/core/events.tsindex a48fb5e2e..03c35d83b 100644--- a/sdk/src/ui/core/events.ts+++ b/sdk/src/ui/core/events.ts@@ -1,5 +1,6 @@import { defineResource } from '../../resource';import type { Entity } from '../../types';+import { log } from '../../logger';/*** Common UI event types. Event type strings are open — users may emit any@@ -248,8 +249,9 @@ export class UIEventQueue {try {h(event);} catch (err) {- console.error(- `[UIEventQueue] handler error [${event.type}]:`,+ log.error(+ 'ui',+ `UIEventQueue handler error [${event.type}]`,err,);}@@ -263,8 +265,9 @@ export class UIEventQueue {try {h(event);} catch (err) {- console.error(- `[UIEventQueue] handler error [${event.type}]:`,+ log.error(+ 'ui',+ `UIEventQueue handler error [${event.type}]`,err,);}diff --git a/sdk/src/wasmError.ts b/sdk/src/wasmError.tsindex 29cce4653..f026a60a4 100644--- a/sdk/src/wasmError.ts+++ b/sdk/src/wasmError.ts@@ -1,3 +1,5 @@+import { log } from './logger';+type WasmErrorHandler = (error: unknown, context: string) => void;let errorHandler: WasmErrorHandler | null = null;@@ -18,12 +20,12 @@ export function handleWasmError(error: unknown, context: string): void {}if (suppressedCount > 0) {- console.warn(`[ESEngine] ${suppressedCount} WASM error(s) suppressed`);+ log.warn('wasm', `${suppressedCount} WASM error(s) suppressed`);suppressedCount = 0;}lastReportTime = now;- console.error(`[ESEngine] WASM error in ${context}:`, error);+ log.error('wasm', `error in ${context}`, error);if (errorHandler) {errorHandler(error, context);}diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.tsindex 02087b1a4..504587627 100644--- a/sdk/src/wechatRuntime.ts+++ b/sdk/src/wechatRuntime.ts@@ -18,6 +18,7 @@ import { SpineManager, type SpineVersion } from './spine/SpineManager';import type { PhysicsWasmModule } from './physics/PhysicsModuleLoader';import type { Vec2 } from './types';import type { SceneData } from './scene';+import { log } from './logger';// =============================================================================// WeChat Asset Provider@@ -90,7 +91,7 @@ function createWasmInstantiator(wasmPath: string) {platformInstantiateWasm(wasmPath, imports).then((result) => {successCallback(result.instance, result.module);}).catch((e) => {- console.error('[WeChat] WASM instantiation failed:', e);+ log.error('wechat', 'WASM instantiation failed', e);});return {};};@@ -105,7 +106,7 @@ async function initWasmModule<T>(instantiateWasm: createWasmInstantiator(wasmPath),});} catch (e) {- console.warn(`[ESEngine] Failed to load WASM module: ${wasmPath}`, e);+ log.warn('wechat', `Failed to load WASM module: ${wasmPath}`, e);return null;}}@@ -142,7 +143,7 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<voconst gl = (canvas.getContext('webgl2') || canvas.getContext('webgl')) as WebGLRenderingContext | null;if (!gl) {- console.error('[ESEngine] Failed to create WebGL context');+ log.error('wechat', 'Failed to create WebGL context');return;}diff --git a/sdk/src/world.ts b/sdk/src/world.tsindex 1269b4f86..b1a65c1f8 100644--- a/sdk/src/world.ts+++ b/sdk/src/world.ts@@ -12,6 +12,7 @@ import { ScriptStorage } from './ecs/ScriptStorage';import { NameIndex } from './ecs/NameIndex';import { ChangeTracker } from './ecs/ChangeTracker';import { QueryCache } from './ecs/QueryCache';+import { log } from './logger';export { PTR_LAYOUTS } from './ptrLayouts.generated';export { BuiltinBridge } from './ecs/BuiltinBridge';@@ -144,7 +145,7 @@ export class World {}for (const cb of this.spawnCallbacks_) {- try { cb(entity); } catch (e) { console.warn('[World] Spawn callback error:', e); }+ try { cb(entity); } catch (e) { log.warn('world', 'Spawn callback error', e); }}return entity;@@ -159,7 +160,7 @@ export class World {}for (const cb of this.despawnCallbacks_) {- try { cb(entity); } catch (e) { console.warn('[World] Despawn callback error:', e); }+ try { cb(entity); } catch (e) { log.warn('world', 'Despawn callback error', e); }}this.names_.remove(entity);@@ -218,7 +219,7 @@ export class World {endIteration(): void {this.iterationDepth_--;if (this.iterationDepth_ < 0) {- console.warn('World.endIteration: mismatched begin/end calls');+ log.warn('world', 'World.endIteration: mismatched begin/end calls');this.iterationDepth_ = 0;}}@@ -478,7 +479,7 @@ export class World {getComponentTypes(entity: Entity): string[] {const types = new Set<string>();for (const [name, methods] of this.builtin_.getMethodCache()) {- try { if (methods.has(entity)) types.add(name); } catch (e) { console.warn(`[World] Component check failed for ${name}:`, e); }+ try { if (methods.has(entity)) types.add(name); } catch (e) { log.warn('world', `Component check failed for ${name}`, e); }}if (this.builtin_.hasCpp) {for (const [name, comp] of getAllRegisteredComponents()) {@@ -486,7 +487,7 @@ export class World {try {const m = this.builtin_.getBuiltinMethods(comp._cppName);if (m.has(entity)) types.add(name);- } catch (e) { console.warn(`[World] Builtin check failed for ${name}:`, e); }+ } catch (e) { log.warn('world', `Builtin check failed for ${name}`, e); }}}}diff --git a/sdk/tests/logger.test.ts b/sdk/tests/logger.test.tsindex aaedab31d..878224c51 100644--- a/sdk/tests/logger.test.ts+++ b/sdk/tests/logger.test.ts@@ -282,10 +282,8 @@ describe('Logger', () => {const spy = vi.spyOn(console, 'log').mockImplementation(() => {});const l = new Logger();l.info('Test', 'msg', { key: 'val' });- expect(spy).toHaveBeenCalledWith(- expect.any(String),- expect.stringContaining('"key":"val"'),- );+ // Single-arg style: non-Error data is JSON-stringified into the line.+ expect(spy).toHaveBeenCalledWith(expect.stringContaining('"key":"val"'));spy.mockRestore();});});diff --git a/sdk/tests/renderPipeline.test.ts b/sdk/tests/renderPipeline.test.tsindex 65152f8d2..fba133ce3 100644--- a/sdk/tests/renderPipeline.test.ts+++ b/sdk/tests/renderPipeline.test.ts@@ -203,7 +203,10 @@ describe('RenderPipeline', () => {pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 0 });- expect(errorSpy).toHaveBeenCalledWith("[CustomDraw] callback 'bad-cb' error:", error);+ expect(errorSpy).toHaveBeenCalledWith(+ expect.stringContaining("callback 'bad-cb' error"),+ error,+ );expect(unregisterDrawCallback).toHaveBeenCalledWith('bad-cb');errorSpy.mockRestore();});diff --git a/sdk/tests/scene.test.ts b/sdk/tests/scene.test.tsindex b9df9cf45..0b282fdf1 100644--- a/sdk/tests/scene.test.ts+++ b/sdk/tests/scene.test.ts@@ -318,7 +318,9 @@ describe('Scene', () => {data: {},});- expect(warnSpy).toHaveBeenCalledWith('Unknown component type: NonExistentComponent');+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('Unknown component type: NonExistentComponent'),+ );warnSpy.mockRestore();});});