easy-logger

簡易的なロギングユーティリティです。

目前为 2022-04-09 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/443079/1038069/easy-logger.js

  1. // ==UserScript==
  2. // @name easy-logger
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0.0
  5. // @license MIT
  6. // @description 簡易的なロギングユーティリティです。
  7. // @author You
  8. // @grant none
  9. // ==/UserScript==
  10.  
  11. class EasyLogger {
  12. static #levels = {
  13. all: { priority: 0, color: 'grey' },
  14. trace: { priority: 1, color: 'blue' },
  15. debug: { priority: 2, color: 'cyan' },
  16. info: { priority: 3, color: 'green' },
  17. warn: { priority: 4, color: 'yellow' },
  18. error: { priority: 5, color: 'red' },
  19. fatal: { priority: 6, color: 'magenta' },
  20. mark: { priority: 7, color: 'grey' },
  21. off: { priority: 8 }
  22. }
  23. #category = 'default'
  24.  
  25. setCategory(category) {
  26. this.#category = category
  27.  
  28. return this
  29. }
  30.  
  31. #level = 'all'
  32. #levelPriority = 0
  33.  
  34. setLevel(level) {
  35. this.#level = level
  36. this.#levelPriority = this.constructor.#levels[level].priority
  37.  
  38. return this
  39. }
  40.  
  41. static #colorReset = '\u001b[0m'
  42. static #colorMap = {
  43. 'grey': '\u001b[90m',
  44. 'blue': '\u001b[34m',
  45. 'cyan': '\u001b[36m',
  46. 'green': '\u001b[32m',
  47. 'yellow': '\u001b[33m',
  48. 'red': '\u001b[31m',
  49. 'magenta': '\u001b[35m'
  50. }
  51.  
  52. static #colorText(text, color) {
  53. return `${this.#colorMap[color]}${text}${this.#colorReset}`
  54. }
  55.  
  56. #createLog(text, level) {
  57. return this.constructor.#colorText(
  58. `[${new Date().toISOString().slice(0, -1)}] [${level.toUpperCase()}] ${this.#category} - ${text}`,
  59. this.constructor.#levels[level].color
  60. )
  61. }
  62.  
  63. #log(text, level) {
  64. if (this.#levelPriority <= this.constructor.#levels[level].priority) {
  65. console.log(this.#createLog(text, level))
  66. }
  67.  
  68. return this
  69. }
  70.  
  71. trace(text) {
  72. return this.#log(text, 'trace')
  73. }
  74.  
  75. debug(text) {
  76. return this.#log(text, 'debug')
  77. }
  78.  
  79. info(text) {
  80. return this.#log(text, 'info')
  81. }
  82.  
  83. warn(text) {
  84. return this.#log(text, 'warn')
  85. }
  86.  
  87. error(text) {
  88. return this.#log(text, 'error')
  89. }
  90.  
  91. fatal(text) {
  92. return this.#log(text, 'fatal')
  93. }
  94.  
  95. mark(text) {
  96. return this.#log(text, 'mark')
  97. }
  98. }
  99.  
  100. window.EasyLogger = EasyLogger