From 768ab84b00f341f6bb039e30b3debc394f99aa1c Mon Sep 17 00:00:00 2001 From: Jeffery Date: Sat, 11 Jul 2026 10:08:52 +0000 Subject: [PATCH] =?UTF-8?q?fix(src/index):=20=E5=85=B1=E7=94=A8=20log=20?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/index.js | 42 ++++++++++++++++++++++++++++++------------ 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/src/index.js b/src/index.js index 2c198f1..092c0f1 100644 --- a/src/index.js +++ b/src/index.js @@ -17,6 +17,34 @@ function section(title) { currentStage = title; } +/** + * 產生統一格式的時間戳記字串。 + * + * @returns {string} Asia/Taipei 時區格式化後的時間戳記。 + * @remarks + * 由 `info()` 與錯誤輸出共用,避免不同輸出路徑各自拼出不同格式。 + */ +function formatTimestamp() { + return new Date() + .toLocaleString('sv-SE', { timeZone: 'Asia/Taipei', hour12: false }) + .replace(/-/g, '/'); +} + +/** + * 以統一格式組裝單行 log。 + * + * @param {string} level 訊息等級。 + * @param {string} message 要輸出的訊息內容。 + * @returns {string} 已格式化完成且含換行的 log 字串。 + * @remarks + * 讓一般資訊與錯誤訊息共用同一套前綴格式,降低未來調整格式時的維護成本。 + */ +function formatLogLine(level, message) { + const stagePrefix = currentStage ? `[${currentStage}]` : ''; + + return `${stagePrefix}[${level}][${formatTimestamp()}]: ${message}\n`; +} + /** * 以統一格式輸出資訊訊息。 * @@ -25,12 +53,7 @@ function section(title) { * 會附加目前階段與 Asia/Taipei 時區時間戳記,適合用於流程進度與狀態輸出。 */ function info(message) { - const timestamp = new Date() - .toLocaleString('sv-SE', { timeZone: 'Asia/Taipei', hour12: false }) - .replace(/-/g, '/'); - const stagePrefix = currentStage ? `[${currentStage}]` : ''; - - process.stdout.write(`${stagePrefix}[INF][${timestamp}]: ${message}\n`); + process.stdout.write(formatLogLine('INF', message)); } /** @@ -398,12 +421,7 @@ async function main() { if (require.main === module) { main().catch((error) => { - const timestamp = new Date() - .toLocaleString('sv-SE', { timeZone: 'Asia/Taipei', hour12: false }) - .replace(/-/g, '/'); - const stagePrefix = currentStage ? `[${currentStage}]` : ''; - - process.stderr.write(`${stagePrefix}[ERR][${timestamp}]: ${error.message}\n`); + process.stderr.write(formatLogLine('ERR', error.message)); process.exit(1); }); }