logger-decorator

provides a unified and simple approach for class and function logging

Usage no npm install needed!

<script type="module">
  import loggerDecorator from 'https://cdn.skypack.dev/logger-decorator';
</script>

README

logger-decorator

Provides a unified and simple approach for class and function logging.

Version Bundle size Downloads

CodeFactor SonarCloud Codacy Total alerts Language grade Scrutinizer

Dependencies Security Build Status Coverage Status

Commit activity FOSSA License

Table of Contents

Requirements

Platform Status

To use library you need to have node and npm installed in your machine:

  • node >=10
  • npm >=6

Package is continuously tested on darwin, linux and win32 platforms. All active and maintenance LTS node releases are supported.

Installation

To install the library run the following command:

  npm i --save logger-decorator

Usage

The package provides a simple decorator, so you can simply wrap functions or classes with it or use @babel/plugin-proposal-decorators in case you love to complicate things.

The recommended way for using 'logger-decorator' is to build own decorator singleton inside the app.

import { Decorator } from 'logger-decorator';

const decorator = new Decorator(config);

Or just use decorator with the default configuration:

import log from 'logger-decorator';

  @log({ level: 'verbose' })
class Rectangle {
      constructor(height, width) {
          this.height = height;
          this.width = width;
      }

      get area() {
          return this.calcArea();
      }

      calcArea() {
          return this.height * this.width;
      }
  }

Configuration

Config must be a JavaScript Object with the following attributes:

  • logger - logger, which build decorator will use, console by default, see logger for more details
  • name - the app name, to include in all logs, could be omitted.

Next values could also be passed to constructor config, but are customizable from decorator(customConfig) invokation:

  • timestamp - if set to true timestamps will be added to all logs.
  • level - default log-level, pay attention that logger must support it as logger.level(smth), 'info' by default. Also function could be passed. The function will receive logged data and should return log-level as string.
  • errorLevel - level, used for errors. 'error' by default. Also function could be passed. The function will receive logged data and should return log-level as string.
  • errorsOnly - if set to true logger will catch only errors.
  • logErrors: next options available:
    • deepest: log only the deepest occurrence of the error. This option prevents 'error spam'
  • paramsSanitizer - function to sanitize input parametrs from sensitive or redundant data, see sanitizers for more details, by default dataSanitizer.
  • resultSanitizer - output data sanitizer, by default dataSanitizer
  • errorSanitizer - error sanitizer, by default simpleSanitizer
  • contextSanitizer - function context sanitizer, if ommited, no context will be logged.
  • dublicates - if set to true, it is possible to use multiple decorators at once (see example)

Next parametrs could help in class method filtering:

  • getters - if set to true, getters will also be logged (applied to class and class-method decorators)
  • setters - if set to true, setters will also be logged (applied to class and class-method decorators)
  • classProperties - if set to true, class-properties will also be logged (applied to class decorators only)
  • include - array with method names, for which logs will be added.
  • exclude - array with method names, for which logs won't be added.
  • methodNameFilter - function, to filter method names

Functions

To decorate a function with logger-decorator the next approach can be applied:

import { Decorator } from 'logger-decorator';

const decorator = new Decorator({ logger });
const decorated = decorator()((a, b) => {
    return a + b;
});

const res = decorated(5, 8); // res === 13
/*
      logger will print:
      { method: 'sum', params: '[ 5, 8 ]', result: '13' }
  */

or, with async functions:

const log = new Decorator({ logger });
const decorated = log({ methodName })(sumAsync);

await decorated(5, 8); // 13

Besides methodName any of the timestamp, level, paramsSanitizer, resultSanitizer, errorSanitizer, contextSanitizer, etc... can be transferred to log(customConfig) and will replace global values.

Classes

To embed logging for all class methods, follow the next approach:

import { Decorator } from 'logger-decorator';
const log = new Decorator();

@log()
class MyClass {
    constructor(config) { // construcor will be ommited
        this.config = config;
    }

    _run(a, b) { // methods, started with underscore will be ommited
        return a + b + 10;
    }

    async run(a, b) { // will be decorated
        const result = this._run(a, b);
        return result * 2;
    }

When needed, the decorator can be applied to a specific class method. It is also possible to use multiple decorators at once:

    const decorator = new Decorator({ logger, contextSanitizer: data => ({ base: data.base }) }); // level info by default

    @decorator({ level: 'verbose', contextSanitizer: data => data.base, dublicates: true })
    class Calculator {
        base = 10;
        _secret = 'x0Hdxx2o1f7WZJ';
        @decorator() // default contextSanitizer have been used
        sum(a, b) {
            return a + b + this.base;
        }
    }

    const calculator = new Calculator();
    calculator.sum(5, 7); // 22
 /*
      next two logs will appear:

      1) level: 'info':
          { params: '[ 5, 7 ]', result: '22', context: { base: 10 } }
      
      2) level: 'verbose':
          { params: '[ 5, 7 ]', result: '22', context: 10 }
  */
    }

Sanitizers

Sanitizer is a function, that recieves data as the first argument, and returns sanitized data. default logger-decorator sanitizers are:

  • simpleSanitizer - default inspect function
  • dataSanitizer - firstly replace all values with key %password% replaced to ***, and then simpleSanitizer.

Performance notes

dataSanitizer could impact performance greatly on complex objects and large arrays. If you don't need to sanitize sensitive patterns (tokens, passwords), use simpleSanitizer, or write a custom handler.

Logger

Logger can be a function, with the next structure:

const logger = (level, data) => {
    console.log(level, data);
};

Otherwise, you can define each logLevel separately in Object / Class logger:

const logger = {
    info    : console.log,
    verbose : console.log,
    error   : console.error
};

Contribute

Make the changes to the code and tests. Then commit to your branch. Be sure to follow the commit message conventions. Read Contributing Guidelines for details.