log-format.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. /**
  2. * 日志格式化工具
  3. *
  4. * 提供统一的时间戳和日志前缀格式化,供所有进程(main/host/server/renderer)使用。
  5. * 纯函数,无 Node.js 专有 API 依赖,浏览器环境安全。
  6. */
  7. /**
  8. * 格式化时间戳为 "YYYY-MM-DD HH:mm:ss.mmm"
  9. */
  10. export function formatTimestamp(date: Date = new Date()): string {
  11. const y = date.getFullYear();
  12. const mo = String(date.getMonth() + 1).padStart(2, "0");
  13. const d = String(date.getDate()).padStart(2, "0");
  14. const h = String(date.getHours()).padStart(2, "0");
  15. const min = String(date.getMinutes()).padStart(2, "0");
  16. const s = String(date.getSeconds()).padStart(2, "0");
  17. const ms = String(date.getMilliseconds()).padStart(3, "0");
  18. return `${y}-${mo}-${d} ${h}:${min}:${s}.${ms}`;
  19. }
  20. /**
  21. * 生成日志前缀,统一格式:
  22. * 有 PID: "[YYYY-MM-DD HH:mm:ss.mmm] [pid:12345] [source]"
  23. * 无 PID: "[YYYY-MM-DD HH:mm:ss.mmm] [source]"
  24. *
  25. * Node.js 进程传入 process.pid,浏览器端不传。
  26. */
  27. export function formatLogPrefix(source: string, pid?: number): string {
  28. const ts = formatTimestamp();
  29. const pidPart = pid != null ? ` [pid:${pid}]` : "";
  30. return `[${ts}]${pidPart} [${source}]`;
  31. }