Skip to content

Commit

Permalink
feat: 自定义日志等级支持
Browse files Browse the repository at this point in the history
  • Loading branch information
TomyJan committed Feb 3, 2024
1 parent c207329 commit fb795c4
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 4 deletions.
38 changes: 38 additions & 0 deletions components/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import fs from 'fs';
import { _CfgPath } from '../data/system/pluginConstants.js';
import kuroLogger from './logger.js';

class ConfigReader {
constructor() {
this.filePath = _CfgPath + '/config.json';
this.configObject = this.readConfig(); // 初始读取配置文件
this.watchConfig(); // 监听配置文件变化
}

readConfig() {
try {
const data = fs.readFileSync(this.filePath, 'utf8');
const configObject = JSON.parse(data);
return configObject;
} catch (error) {
kuroLogger.error('读取配置文件失败:', error.message);
return {};
}
}

watchConfig() {
fs.watchFile(this.filePath, (curr, prev) => {
if (curr.mtime > prev.mtime) {
this.configObject = this.readConfig();
kuroLogger.info('配置文件已更新');
kuroLogger.setLogLevel(this.configObject.logger.logLevel);
}
});
}

getConfig() {
return this.configObject;
}
}

export default new ConfigReader().readConfig();
8 changes: 5 additions & 3 deletions components/logger.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import chalk from 'chalk'
import fs from 'fs'
import path from 'path'
import { dataPath, pluginVer } from '../data/system/pluginConstants.js'
import { dataPath } from '../data/system/pluginConstants.js'
import config from './config.js'

class Logger {
constructor(
logLevel = pluginVer.slice(-3) === 'rel' ? 'info' : 'debug',
logLevel = config.logger.logLevel || 'info',
logDirectory = dataPath + '/logs'
) {
this.logLevel = logLevel.toLowerCase()
Expand Down Expand Up @@ -94,7 +95,8 @@ class Logger {
}

// 初始化全局日志记录器实例
const kuroLogger = new Logger('debug')
console.log(JSON.stringify(config))
const kuroLogger = new Logger(config.logger.logLevel || 'info')
logger.info(chalk.gray(`[库洛插件][LOGGER] Logger initialized!`))

export default kuroLogger
4 changes: 3 additions & 1 deletion guoba.support.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,10 @@ export function supportGuoba() {

// 比较配置文件更新
let testConfigJson = mergeObjects(defaultConfigJson, configJson)
if (testConfigJson !== configJson) {
if (JSON.stringify(testConfigJson) !== JSON.stringify(configJson)) {
kuroLogger.warn('配置文件有更新, 建议检查是否有新的项目需要配置!')
kuroLogger.debug('testConfigJson:', JSON.stringify(testConfigJson))
kuroLogger.debug('configJson:', JSON.stringify(configJson))
configJson = testConfigJson
updateConfigFile()
sendMsgFriend(
Expand Down

0 comments on commit fb795c4

Please sign in to comment.