|
| 1 | +const fs = require("fs"); |
| 2 | +const moment = require("moment"); |
| 3 | + |
| 4 | +let MAIN_DIRECTORY = __dirname.replace(/\\/g, '/').replace("/node_modules/error-printer", ""); |
| 5 | +let OPTIONS = { |
| 6 | + logFileName: "error_log", |
| 7 | + messageTitle: "Error message", |
| 8 | + codeTitle: "Error code", |
| 9 | + datePureTitle: "Error Date ( Pure )", |
| 10 | + dateFormattedTitle: "Error Date ( Formatted )", |
| 11 | + formattedDateConfig: "DD MMMM YYYY hh:mm A", |
| 12 | + isWriteCode: true, |
| 13 | + isWritePureDate: true, |
| 14 | + isWriteFormattedDate: true |
| 15 | +}; |
| 16 | + |
| 17 | +const setMainDirectory = (directory) => { |
| 18 | + MAIN_DIRECTORY = directory; |
| 19 | +} |
| 20 | + |
| 21 | +const setOptions = (options) => { |
| 22 | + OPTIONS = { |
| 23 | + ...OPTIONS, |
| 24 | + ...options |
| 25 | + } |
| 26 | +}; |
| 27 | + |
| 28 | +const error_log = ({ |
| 29 | + options, |
| 30 | + message, |
| 31 | + code |
| 32 | +}) => { |
| 33 | + const _options = { |
| 34 | + ...OPTIONS, |
| 35 | + ...options |
| 36 | + }; |
| 37 | + |
| 38 | + // Error file exists control: |
| 39 | + const fileExists = fs.existsSync(MAIN_DIRECTORY + `/${_options.logFileName}`); |
| 40 | + |
| 41 | + // If error file do not exists, it will be create: |
| 42 | + if (!fileExists) { |
| 43 | + fs.writeFileSync(MAIN_DIRECTORY + `/${_options.logFileName}`, ""); |
| 44 | + } |
| 45 | + |
| 46 | + // Error message: |
| 47 | + let errorData = ` |
| 48 | +${_options.messageTitle}: ${message} |
| 49 | +`; |
| 50 | + |
| 51 | + if (_options.isWriteCode) { |
| 52 | + errorData += `${_options.codeTitle}: ${code}`; |
| 53 | + } |
| 54 | + |
| 55 | + if (_options.isWritePureDate) { |
| 56 | + errorData += `${_options.datePureTitle}: ${new Date().toISOString()}\n`; |
| 57 | + } |
| 58 | + |
| 59 | + if (_options.isWriteFormattedDate) { |
| 60 | + errorData += `${_options.dateFormattedTitle}: ${moment(new Date()).format(_options.formattedDateConfig)}\n`; |
| 61 | + } |
| 62 | + |
| 63 | + errorData += `\n`; |
| 64 | + |
| 65 | + // Write new error message to error_log file. |
| 66 | + fs.appendFile(MAIN_DIRECTORY + `/${_options.logFileName}`, errorData, err => { |
| 67 | + if (err) { |
| 68 | + console.error(err); |
| 69 | + return err; |
| 70 | + } |
| 71 | + }); |
| 72 | +}; |
| 73 | + |
| 74 | +module.exports = error_log; |
| 75 | +module.exports.setMainDirectory = setMainDirectory; |
| 76 | +module.exports.setOptions = setOptions; |
0 commit comments