logger-decorator
v1.8.1
Published
provides a unified and simple approach for class and function logging
Downloads
4,551
Maintainers
Readme
logger-decorator
Provides a unified and simple approach for class and function logging.
🇺🇦 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
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 passingkeepReflectMetadata
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 functiondataSanitizer
- firstly replace all values with key%password%
replaced to***
, and thensimpleSanitizer
.
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.