"use strict"; /* * 月次ローテーションするローカルログファイルへの書き込み。 * 出力先: LOG_LOCAL_DIR/backup-YYYYMM.log (月が変わると自動的に別ファイルへ切り替わる) * 各行: YYYY-MM-DD HH:mm:ss [LEVEL] message */ const fs = require("fs"); const path = require("path"); function pad(n, width = 2) { return String(n).padStart(width, "0"); } function timestamp(date = new Date()) { return ( `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}` ); } // LOG_LOCAL_DIR は実行時に .env 読み込み後の process.env を見たいため、 // モジュール読み込み時点では確定させず呼び出しの都度評価する。 function getLogDir() { return process.env.LOG_LOCAL_DIR ? path.resolve(process.env.LOG_LOCAL_DIR) : path.join(__dirname, "..", "logs"); } function currentLogFilePath(date = new Date()) { const yyyymm = `${date.getFullYear()}${pad(date.getMonth() + 1)}`; return path.join(getLogDir(), `backup-${yyyymm}.log`); } function writeLine(level, message) { const line = `${timestamp()} [${level}] ${message}`; if (level === "WARN") { console.warn(line); } else if (level === "ERROR") { console.error(line); } else { console.log(line); } try { const logDir = getLogDir(); fs.mkdirSync(logDir, { recursive: true }); fs.appendFileSync(currentLogFilePath(), line + "\n", "utf8"); } catch (err) { console.error(`[logger] ログファイルへの書き込みに失敗しました: ${err.message}`); } } module.exports = { info: (message) => writeLine("INFO", message), warn: (message) => writeLine("WARN", message), error: (message) => writeLine("ERROR", message), currentLogFilePath, getLogDir, };