logger.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * https://github.com/megahertz/electron-log
  3. * - [Linux] ~/.config/v3-electron-vite/logs
  4. * - [macOS] ~/Library/Logs/v3-electron-vite
  5. * - [Windows] %USERPROFILE%\AppData\Roaming\v3-electron-vite\logs
  6. */
  7. import eleLog from "electron-log"
  8. //#region 配置
  9. /** 可选项, 调用后可在渲染进程使用 window.__electronLog */
  10. eleLog.initialize()
  11. /** 设置日志文件等级, 默认为 silly */
  12. eleLog.transports.file.level = "info"
  13. /**
  14. * 设置日志文件大小 1048576 (1M)
  15. * 达到规定大小, 备份文件并重命名为 {name}.old.log
  16. * 有且仅有一个备份日志文件
  17. */
  18. eleLog.transports.file.maxSize = 1048576
  19. /** 设置日志文件的数据格式 */
  20. eleLog.transports.file.format = `[{y}-{m}-{d} {h}:{i}:{s}.{ms}] {text}`
  21. /** 设置日志控制台等级, 默认为 silly */
  22. eleLog.transports.console.level = "info"
  23. eleLog.transports.console.format = `[{h}:{i}:{s}.{ms}] {text}`
  24. //#endregion
  25. /** 日志工厂 */
  26. class LogFactory {
  27. /** 文件名称 */
  28. private fileName: string
  29. /** 日志器实例 */
  30. private logInst: any
  31. /** 构造函数 */
  32. constructor(name: string) {
  33. this.fileName = name + ".log"
  34. this.logInst = eleLog.create({ logId: name })
  35. this.logInst.transports.file.fileName = this.fileName
  36. this.logInst.transports.file.format = `[{y}-{m}-{d} {h}:{i}:{s}.{ms}] {text}`
  37. this.logInst.transports.console.level = false
  38. // 禁止修改
  39. Object.freeze(this)
  40. }
  41. /** 统一处理, 可在这里对日志进行加密 */
  42. private handle(type: string, ...params: any[]) {
  43. try {
  44. this.logInst[type]("\n", ...params, "\n")
  45. } catch (reason: any) {
  46. console.log("\n\n[LogFactory.handle] ", reason)
  47. }
  48. }
  49. //#region 日志方法
  50. log(...params: any[]) {
  51. this.handle("log", ...params)
  52. }
  53. info(...params: any[]) {
  54. this.handle("info", ...params)
  55. }
  56. error(...params: any[]) {
  57. this.handle("error", ...params)
  58. }
  59. warn(...params: any[]) {
  60. this.handle("warn", ...params)
  61. }
  62. verbose(...params: any[]) {
  63. this.handle("verbose", ...params)
  64. }
  65. debug(...params: any[]) {
  66. this.handle("debug", ...params)
  67. }
  68. silly(...params: any[]) {
  69. this.handle("silly", ...params)
  70. }
  71. //#endregion
  72. }
  73. export const mainLog = new LogFactory("main")
  74. export const requestLog = new LogFactory("request")
  75. export const exceptionLog = new LogFactory("exception")