log-writer.js 748 B

123456789101112131415161718192021222324252627282930
  1. import { LOG_DIR } from './log-path.js';
  2. import path from 'path';
  3. import fs from 'fs';
  4. const MAX_SIZE = 2 * 1024 * 1024; // 2 MB
  5. function getBaseName() {
  6. return new Date().toISOString().slice(0, 10);
  7. }
  8. function pad(n) { return n.toString().padStart(3, '0'); }
  9. function currentLogFile() {
  10. let idx = 0;
  11. while (true) {
  12. const name = `${getBaseName()}_${pad(idx)}.log`;
  13. const p = path.join(LOG_DIR, name);
  14. try {
  15. const stat = fs.statSync(p);
  16. if (stat.size < MAX_SIZE) return p;
  17. idx++;
  18. } catch {
  19. return p; // 文件不存在,直接用它
  20. }
  21. }
  22. }
  23. export function writeLog(level, msg) {
  24. const line = `[${new Date().toISOString()}] [${level}] ${msg}\n`;
  25. fs.appendFileSync(currentLogFile(), line);
  26. }