Skip to content

Commit

Permalink
feat: can load custom log4js config log4js.json
Browse files Browse the repository at this point in the history
- Load custom `log4js.json` if exists in config directory
- Load default `log4js.default.json` config
when `log4js.json` is not exists
  • Loading branch information
Chinlinlee committed Aug 8, 2022
1 parent 0a46a5a commit c05c372
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 2 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,5 @@ tempScript
/public/scripts/config.js

#ignore config file of pluginsConfig
/plugins/config.js
/plugins/config.js
/config/log4js.json
79 changes: 79 additions & 0 deletions utils/fileExist.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
const { promises, statSync, Stats } = require("fs");

/**
* @typedef Error
* @property {string} code
*/

/**
* @typedef Options
* @property {boolean} includeDirectories
*/


/**
*
* @param {Error} e
* @returns
*/
function handleError(e) {
if (e.code === "ENOENT") {
return false;
} else {
return undefined;
}
}

/**
*
* @param {Stats} result
* @param {Options} options
* @returns
*/
function handleResult(result, options) {
return (
result.isFile() ||
Boolean(options?.includeDirectories && result.isDirectory())
);
}

/**
* asynchronous function for checking file is exists
* @param {string} path
* @param {Options} options
* @returns {boolean}
*/
async function fileExists(
path,
options = {}
) {
return promises
.stat(path)
.then((result) => {
return handleResult(result, options);
})
.catch((e) => {
return handleError(e);
});
}

/**
* synchronous function for checking file is exists
* @param {string} path
* @param {Options} options
* @returns {boolean}
*/
function fileExistsSync(
path,
options
) {
try {
const result = statSync(path);
return handleResult(result, options);
} catch (e) {
return handleError(e);
}
}

module.exports.fileExists = fileExists;
module.exports.fileExistsSync = fileExistsSync;
9 changes: 8 additions & 1 deletion utils/log.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
const fs = require('fs');
const path = require('path');
const { fileExistsSync } = require("./fileExist");
const { configure, getLogger } = require('log4js');
configure(path.join(__dirname, "../config/log4js.default.json"));
const USER_LOG_CONFIG_FILENAME = path.join(__dirname, "../config/log4js.json");
const DEFAULT_LOG_CONFIG_FILENAME = path.join(__dirname, "../config/log4js.default.json");
if (fileExistsSync(USER_LOG_CONFIG_FILENAME)) {
configure(USER_LOG_CONFIG_FILENAME);
} else {
configure(DEFAULT_LOG_CONFIG_FILENAME);
}
let raccoonLogger = getLogger();

module.exports.logger = raccoonLogger;

0 comments on commit c05c372

Please sign in to comment.