npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

logger-decorator

v1.8.1

Published

provides a unified and simple approach for class and function logging

Downloads

10,929

Readme

Logo

logger-decorator

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

Version Bundle size Downloads

CodeFactor SonarCloud Codacy Scrutinizer

Dependencies Security Build Status Coverage Status

Commit activity FOSSA License Made in Ukraine

🇺🇦 Help Ukraine

I woke up on my 26th birthday at 5 am from the blows of russian missiles. They attacked the city of Kyiv, where I live, as well as the cities in which my family and friends live. Now my country is a war zone.

We fight for democratic values, freedom, for our future! Once again Ukrainians have to stand against evil, terror, against genocide. The outcome of this war will determine what path human history is taking from now on.

💛💙 Help Ukraine! We need your support! There are dozen ways to help us, just do it!

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 - the logger that the build decorator will use. console by default; see logger for more details.
  • name - the app name to include in all logs; it could be omitted.

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

  • timestamp - if set to true, timestamps will be added to all logs.
  • level - the default log-level; pay attention that the logger must support it as logger.level(smth), 'info' by default. Also, a function could be passed. The function will receive logged data and should return the log-level as a string.
  • errorLevel - the level used for errors; 'error' by default. Also, a function could be passed. The function will receive logged data and should return the log-level as a string.
  • paramsLevel - the level used for logging params. Logger will print input params before the function starts executing. Also, a function could be passed. The function will receive logged data and should return the log-level as a string. If omitted, nothing will be logged before execution.
  • errorsOnly - if set to true, the 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 parameters 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 omitted, no context will be logged.
  • duplicates - if set to true, it is possible to use multiple decorators at once (see example).
  • keepReflectMetadata - if logger-decorator is used with other decorators, they can set own reflect metadata. By passing keepReflectMetadata array, you can prevent metadata from resetting. For example, for NestJS, it's a good idea to use { keepReflectMetadata: ['method', 'path'] }.

Next parameters 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.