Skip to content

Plugins

Manolo Edge edited this page Jan 19, 2020 · 2 revisions

Version v1.1.0 added the support for creating plugins (fairly simple at the moment), but will be improving over time.

Every entity is pluginizable apart from the Pipe and Log.

Here is a little overview of what that means:

// Add custom Severity
const { Severity, severity } = require('loggin-js');
Severity.register(10, 'CUSTOM');

// It can then be used as follows
Severity.get(10);
Severity.get('CUSTOM');
Severity.CUSTOM;

severity(10);

Creating a plugin

Creating a plugin is rather easy, it's just a function that registers or modifies the LogginJS Library. For example the following example adds a new custom Severity:

// plugin.js
function myFirstPlugin(loggin){
    const { Severity, Formatter } = loggin;

    Severity.register(10, 'CUSTOM');

    Formatter.replaceables.push({
        regexp: /CUS|CUSTOM|<%m[^>]+>/g,
        fn: (str) => clicolor.magentaBright(str).replace(/<%m(.+)>/g, '$1')
    });
}
module.exports = myFirstPlugin;

Let me break this done into pieces.

First we create and export a function, which receives loggin as an argument, wich resolves to LogginJS:

function myFirstPlugin(loggin){ }
module.exports = myFirstPlugin;

Now inside the function I recommend spreading the lib, for less convoluted code, although this is personal taste and style:

const { Severity, Formatter } = loggin;

The following step is the one doing the work here, it basically registers a new Severity into the library, so it can be use anywhere, first argument is a integer which determines the log level, following rfc3164, and a string representing the name of the severity:

Severity.register(10, 'CUSTOM');

At the end a new replaceable is added to the Formatter.replaceables array, this is just so the Severity we just created gets colored, when color is active in the logger.

    Formatter.replaceables.push({
        regexp: /CUS|CUSTOM|<%m[^>]+>/g,         // Pattern that will get replaced
        fn: (str) => clicolor.magentaBright(str) // Function that replaces match with colored string
    });

And our plugin is set! Now we can added it into the lib:

// app.js
const loggin = require('loggin-js');
const myFirstPlugin = require('plugin.js');

loggin.use(myFirstPlugin);

// Now the severity is available and can be used
loggin.severity('custom');
loggin.severity(10);