|
| 1 | +--- |
| 2 | +sidebar_position: 4 |
| 3 | +--- |
| 4 | + |
| 5 | +# 自定義日誌 |
| 6 | + |
| 7 | +一個屬於擴充自己的日誌紀錄方式。 |
| 8 | + |
| 9 | +## index.js |
| 10 | + |
| 11 | +```js |
| 12 | +const { TREM, Logger, MixinManager } = this.#ctx; |
| 13 | +// 傳入主視窗 Logger 類定義 (父類) |
| 14 | +// 導入新的自定義類 (繼承的子類) |
| 15 | +const { CustomLogger } = require("./logger").createCustomLogger(Logger); |
| 16 | +// 初始化自定義類 |
| 17 | +this.logger = new CustomLogger("example"); |
| 18 | +this.logger.info("info"); |
| 19 | +``` |
| 20 | + |
| 21 | +## test.js |
| 22 | + |
| 23 | +```js |
| 24 | +// 由於是單例模式,在 index.js 初始化後,即可在任何地方使用。 |
| 25 | +const logger = require("./logger"); |
| 26 | +logger.info("info"); |
| 27 | +``` |
| 28 | + |
| 29 | +## logger.js |
| 30 | + |
| 31 | +```js |
| 32 | +let globalInstance = null; |
| 33 | +let CustomLoggerClass = null; |
| 34 | + |
| 35 | +function createCustomLogger(BaseLogger) { |
| 36 | + if (CustomLoggerClass && globalInstance) |
| 37 | + return { |
| 38 | + CustomLogger: CustomLoggerClass, |
| 39 | + instance: globalInstance, |
| 40 | + }; |
| 41 | + |
| 42 | + class CustomLogger extends BaseLogger { |
| 43 | + constructor(prefix = "") { |
| 44 | + super(); |
| 45 | + |
| 46 | + if (globalInstance) { |
| 47 | + globalInstance.prefix = prefix; |
| 48 | + return globalInstance; |
| 49 | + } |
| 50 | + |
| 51 | + this.prefix = prefix; |
| 52 | + globalInstance = this; |
| 53 | + } |
| 54 | + |
| 55 | + _formatMessage(message, ...args) { |
| 56 | + const formattedMessage = super._formatMessage(message, ...args); |
| 57 | + return this.prefix |
| 58 | + ? `[${this.prefix}] ${formattedMessage}` |
| 59 | + : formattedMessage; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + CustomLoggerClass = CustomLogger; |
| 64 | + |
| 65 | + return { |
| 66 | + CustomLogger, |
| 67 | + instance: globalInstance, |
| 68 | + }; |
| 69 | +} |
| 70 | + |
| 71 | +function checkInitialized() { |
| 72 | + if (!globalInstance) |
| 73 | + throw new Error( |
| 74 | + "Logger not initialized. Please call createCustomLogger first." |
| 75 | + ); |
| 76 | +} |
| 77 | + |
| 78 | +module.exports = { |
| 79 | + createCustomLogger, |
| 80 | + info: (...args) => { |
| 81 | + checkInitialized(); |
| 82 | + return globalInstance.info(...args); |
| 83 | + }, |
| 84 | + error: (...args) => { |
| 85 | + checkInitialized(); |
| 86 | + return globalInstance.error(...args); |
| 87 | + }, |
| 88 | + warn: (...args) => { |
| 89 | + checkInitialized(); |
| 90 | + return globalInstance.warn(...args); |
| 91 | + }, |
| 92 | + debug: (...args) => { |
| 93 | + checkInitialized(); |
| 94 | + return globalInstance.debug(...args); |
| 95 | + }, |
| 96 | + get prefix() { |
| 97 | + checkInitialized(); |
| 98 | + return globalInstance.prefix; |
| 99 | + }, |
| 100 | +}; |
| 101 | +``` |
0 commit comments