Compare commits

..

No commits in common. "0c155c365ed1a4c3a1cef081f03d0b610dba33af" and "28a888ce7b2f9ff09987bab51bb6f954a0288926" have entirely different histories.

8 changed files with 48 additions and 78 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
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 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
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,10 +30,3 @@ 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.4", "version": "1.2.3",
"description": "Logging thing", "description": "Logging thing",
"main": "index.js", "main": "index.js",
"author": "Navy.gif", "author": "Navy.gif",

View File

@ -30,26 +30,12 @@ module.exports = {
customStreams: [], customStreams: [],
customTypeMapping: {}, customTypeMapping: {},
customColors: {}, customColors: {},
guard: '_logger', debug: false,
logLevel: 1, guard: '_logger'
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,10 +4,6 @@ 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;
@ -26,28 +22,14 @@ class LoggerClient {
}); });
} }
this.#_guard = opts.guard || Defaults.ClientOptions.guard; this.guard = opts.guard || Defaults.ClientOptions.guard;
this.#_logLevel = opts.logLevel || Defaults.ClientOptions.logLevel; this._debug = opts.debug || Defaults.ClientOptions.debug;
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 (this.#_logLevelMapping[opts.type] < this.#_logLevel) if (opts.type === 'debug' && !this._debug)
return; return;
if (typeof message !== 'string') if (typeof message !== 'string')
@ -60,7 +42,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,27 +10,36 @@ 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 {
#_guard = null; constructor ({
#_logLevel = null; directory = './logs',
#_logLevelMapping = null; customTypes = [],
customStreams = [],
constructor (config = Defaults.MasterOptions) { customTypeMapping = {},
customColors = {},
const { debug = false,
directory, customTypes, customStreams, customTypeMapping, guard = '_logger',
customColors, guard, fileRotationFreq, logLevel, logLevelMapping fileRotationFreq = 1
} = { ...Defaults.MasterOptions, ...config }; } = DefaultOpts) {
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.#_logLevel = logLevel; this._debug = debug;
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) {
@ -52,11 +61,13 @@ 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 });
@ -77,8 +88,7 @@ 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,16 +1,16 @@
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 < 5; i++) { for (let i = 0; i < 10000; 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');

View File

@ -16,8 +16,7 @@ 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);