Compare commits

..

2 Commits

Author SHA1 Message Date
0c155c365e
v1.2.4 2023-03-26 20:38:35 +03:00
a5cc118878
changed debug option to loglevel option 2023-03-26 20:38:15 +03:00
8 changed files with 78 additions and 48 deletions

View File

@ -76,10 +76,10 @@
], ],
"lines-around-comment": "warn", "lines-around-comment": "warn",
"lines-around-directive": "warn", "lines-around-directive": "warn",
"lines-between-class-members": [ // "lines-between-class-members": [
"warn", // "warn",
"always" // "always"
], // ],
"max-classes-per-file": "warn", "max-classes-per-file": "warn",
"max-nested-callbacks": "warn", "max-nested-callbacks": "warn",
"new-parens": "warn", "new-parens": "warn",

View File

@ -20,7 +20,7 @@ The child processes are expected to be attached with the attach() method found i
{ {
//////// SHARED BETWEEN CLIENT & MASTER //////// SHARED BETWEEN CLIENT & MASTER
guard: '_logger', // Message guard, e.g this property has to be true in the IPC message for the logger to read it guard: '_logger', // Message guard, e.g this property has to be true in the IPC message for the logger to read it
debug: false, // On the master logger this determines whether the output is written to console (i.e. will always be written to file), on the client this determines whether it is sent to the master at all loglevel: false, // On the master logger this determines whether the output is written to console (i.e. will always be written to file), on the client this determines whether it is sent to the master at all
customTypes: [], // Log types, defaults are 'error', 'warn', 'info', 'debug', 'status'. Each one of these has an associated shorthand function, the custom ones will receive one too, e.g. adding 'access' to the custom types will add a logger.access() function customTypes: [], // Log types, defaults are 'error', 'warn', 'info', 'debug', 'status'. Each one of these has an associated shorthand function, the custom ones will receive one too, e.g. adding 'access' to the custom types will add a logger.access() function
/////// MASTER EXCLUSIVE /////// MASTER EXCLUSIVE
customStreams: [], // File streams, by default there are streams for error and default customStreams: [], // File streams, by default there are streams for error and default
@ -30,3 +30,10 @@ The child processes are expected to be attached with the attach() method found i
directory: './logs', // Directory in which to write log files directory: './logs', // Directory in which to write log files
} }
``` ```
**Log levels**
0 - Debug
1 - Info
2 - Status
3 - Warning
4 - Error

View File

@ -1,6 +1,6 @@
{ {
"name": "@navy.gif/logger", "name": "@navy.gif/logger",
"version": "1.2.3", "version": "1.2.4",
"description": "Logging thing", "description": "Logging thing",
"main": "index.js", "main": "index.js",
"author": "Navy.gif", "author": "Navy.gif",

View File

@ -30,12 +30,26 @@ module.exports = {
customStreams: [], customStreams: [],
customTypeMapping: {}, customTypeMapping: {},
customColors: {}, customColors: {},
debug: false, guard: '_logger',
guard: '_logger' logLevel: 1,
logLevelMapping: {
debug: 0,
info: 1,
status: 2,
warn: 3,
error: 4
}
}, },
ClientOptions: { ClientOptions: {
debug: true,
guard: '_logger', guard: '_logger',
customStreams: [] customStreams: [],
logLevel: 1,
logLevelMapping: {
debug: 0,
info: 1,
status: 2,
warn: 3,
error: 4
}
} }
}; };

View File

@ -4,6 +4,10 @@ class LoggerClient {
static MaxChars = 0; static MaxChars = 0;
#_guard = null;
#_logLevel = null;
#_logLevelMapping = null;
constructor (opts = Defaults.ClientOptions) { constructor (opts = Defaults.ClientOptions) {
this.name = opts.name || opts.constructor.name; this.name = opts.name || opts.constructor.name;
@ -22,14 +26,28 @@ class LoggerClient {
}); });
} }
this.guard = opts.guard || Defaults.ClientOptions.guard; this.#_guard = opts.guard || Defaults.ClientOptions.guard;
this._debug = opts.debug || Defaults.ClientOptions.debug; this.#_logLevel = opts.logLevel || Defaults.ClientOptions.logLevel;
this.#_logLevelMapping = { ...Defaults.ClientOptions.logLevelMapping, ...opts.logLevelMapping };
} }
get logLevel () {
return this.#_logLevel;
}
setLogLevel (level = 'info') {
if (typeof level === 'number')
this.#_logLevel = level;
else if (typeof level === 'string')
this.#_logLevel = this.#_logLevelMapping[level.toLowerCase()];
else
throw new Error(`Invalid log level type, expected string or number, got ${typeof level}`);
}
transport (message, opts) { transport (message, opts) {
if (opts.type === 'debug' && !this._debug) if (this.#_logLevelMapping[opts.type] < this.#_logLevel)
return; return;
if (typeof message !== 'string') if (typeof message !== 'string')
@ -42,7 +60,7 @@ class LoggerClient {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log(`${header} ${message}`); console.log(`${header} ${message}`);
else else
process.send({ [this.guard]: true, header, message, ...opts }); process.send({ [this.#_guard]: true, header, message, ...opts });
} }

View File

@ -10,36 +10,27 @@ const Defaults = require('./Defaults');
const DAY = 1000 * 60 * 60 * 24; const DAY = 1000 * 60 * 60 * 24;
const DefaultOpts = {
fileRotationFreq: 1,
directory: './logs',
customTypes: [],
customStreams: [],
customTypeMapping: {},
customColors: {},
debug: false,
guard: '_logger'
};
// TODO: // TODO:
// - Discord webhook, need to write a separate package for that, don't want to add the entirety of d.js as a dep just for a webhook // - Discord webhook, need to write a separate package for that, don't want to add the entirety of d.js as a dep just for a webhook
class MasterLogger { class MasterLogger {
constructor ({ #_guard = null;
directory = './logs', #_logLevel = null;
customTypes = [], #_logLevelMapping = null;
customStreams = [],
customTypeMapping = {}, constructor (config = Defaults.MasterOptions) {
customColors = {},
debug = false, const {
guard = '_logger', directory, customTypes, customStreams, customTypeMapping,
fileRotationFreq = 1 customColors, guard, fileRotationFreq, logLevel, logLevelMapping
} = DefaultOpts) { } = { ...Defaults.MasterOptions, ...config };
this.directory = path.resolve(directory); this.directory = path.resolve(directory);
if (!fs.existsSync(this.directory)) if (!fs.existsSync(this.directory))
fs.mkdirSync(this.directory, { recursive: true }); fs.mkdirSync(this.directory, { recursive: true });
this._debug = debug; this.#_logLevel = logLevel;
this.#_logLevelMapping = { ...Defaults.MasterOptions.logLevelMapping, ...logLevelMapping };
this.#_guard = guard;
this.types = [ ...customTypes, ...Defaults.Types ]; this.types = [ ...customTypes, ...Defaults.Types ];
for (const type of this.types) { for (const type of this.types) {
@ -61,13 +52,11 @@ class MasterLogger {
this.startDay = Math.floor(Date.now() / this.rotationFreq) * this.rotationFreq; this.startDay = Math.floor(Date.now() / this.rotationFreq) * this.rotationFreq;
this.rotateTO = setTimeout(this.rotateLogFiles.bind(this), this.startDay + this.rotationFreq - Date.now()); this.rotateTO = setTimeout(this.rotateLogFiles.bind(this), this.startDay + this.rotationFreq - Date.now());
this.guard = guard;
} }
attach (shard) { attach (shard) {
shard.on('message', (msg) => { shard.on('message', (msg) => {
if (!msg[this.guard]) if (!msg[this.#_guard])
return; return;
const { message, type, header, broadcast } = msg; const { message, type, header, broadcast } = msg;
this[type](message, { subheader: header, shard, broadcast }); this[type](message, { subheader: header, shard, broadcast });
@ -88,7 +77,8 @@ class MasterLogger {
const maxChars = Math.max(...this.types.map(t => t.length)); const maxChars = Math.max(...this.types.map(t => t.length));
const spacer = ' '.repeat(maxChars - type.length); const spacer = ' '.repeat(maxChars - type.length);
if (type === 'debug' && this._debug || type !== 'debug') // if (type === 'debug' && this._debug || type !== 'debug')
if (this.#_logLevelMapping[type] >= this.#_logLevel)
console.log(`${chalk[colour](type)}${spacer} ${chalk[colour](header)}: ${chalk.bold(subheader)}${text}`); // eslint-disable-line no-console console.log(`${chalk[colour](type)}${spacer} ${chalk[colour](header)}: ${chalk.bold(subheader)}${text}`); // eslint-disable-line no-console
if (broadcast) { if (broadcast) {

View File

@ -1,17 +1,17 @@
const { LoggerClient } = require('../'); const { LoggerClient } = require('../');
const logger = new LoggerClient({ const logger = new LoggerClient({
debug: true,
customTypes: [ 'access' ], customTypes: [ 'access' ],
customStreams: [ 'access' ], customStreams: [ 'access' ],
customTypeMapping: { access: 'access', warn: 'error' }, customTypeMapping: { access: 'access', warn: 'error' },
customColors: { access: 'green' } customColors: { access: 'green' },
logLevelMapping: { access: 2 }
}); });
const main = async () => { const main = async () => {
for (let i = 0; i < 10000; i++) { for (let i = 0; i < 5; i++) {
if (i % 500 === 0) // if (i % 500 === 0)
await new Promise(resolve => setTimeout(resolve, 1000)); await new Promise(resolve => setTimeout(resolve, 1000));
logger.info('Info test'); logger.info('Info test');
logger.status('Status test'); logger.status('Status test');
logger.debug('Debug test'); logger.debug('Debug test');

View File

@ -16,7 +16,8 @@ const main = async () => {
customStreams: [ 'access' ], customStreams: [ 'access' ],
customTypeMapping: { access: 'access', warn: 'error' }, customTypeMapping: { access: 'access', warn: 'error' },
customColors: { access: 'green' }, customColors: { access: 'green' },
fileRotationFreq: 0.0001 fileRotationFreq: 0.0001,
logLevelMapping: { access: 2 }
}); });
const child = ChildProcess.fork('./test/otherProcess.js'); const child = ChildProcess.fork('./test/otherProcess.js');
logger.attach(child); logger.attach(child);