Boilerplate-free decorator-based class logging. Log method calls and creation of your class easily with the help of two decorators. No prototype mutation. Highly configurable. Built with TypeScript. Works with Node.js and in browser.
Logs Test.construct. Args: [].
before a class instance is created.
Logs Test.method1. Args: [].
before the method call.
Logs Test.method1 -> done. Args: []. Res: 123.
after it.
- Installation
- Requirements
- Quick start (Live demo)
- Configuration
- Configuration object
- Hierarchical config (Live demo)
- Include
- Examples
- Disable logging of arguments for all messages
- Disable logging of arguments for end messages
- Enable logging of a formatted class instance for all messages
- Enable logging of a formatted class instance for end messages
- Disable logging of class construction
- Disable logging of method's return value (or thrown error)
- Change logger
- Formatting
Installation
-
Run
npm i class-logger reflect-metadata
-
If you use TypeScript set in you tsconfig.json
-
If you use JavaScript configure your babel to support decorators and class properties
-
At the top of your project root file add
Requirements
Your environment must support Proxy. For Node.js it's 6.4.0+, for browsers it's Edge 12+, Firefox 18+, Chrome 49+, Safari 10+.
(Live demo)
Quick startYou can log:
- Class construction
- Prototype and static method calls, both: synchronous and asynchronous. Any thrown errors are properly logged and re-thrown.
- Own and static property calls if those properties return functions (synchronous or asynchronous). Error handling is the same as for method calls.
// Logs to the console before the method call:// 'Test.methodStatic1. Args: [42].'Test.methodStatic142// Logs to the console after the method call:// 'Test.methodStatic1 -> done. Args: [42]. Res: {"prop1":"test"}.' // Logs to the console before the class' construction:// 'Test.construct. Args: [].' // Logs to the console before the method call:// 'Test.method1. Args: [].'test.method1// Logs to the console after the method call:// 'Test.method1 -> done. Args: []. Res: 123.' // Logs to the console before the method call:// 'Test.methodAsync1. Args: [].'test.methodAsync1// Logs to the console after the method call (after the promise is resolved):// 'Test.methodAsync1 -> done. Args: []. Res: Symbol().' // Logs to the console before the method call:// 'Test.methodError. Args: [].'test.methodError// Logs to the console after the method call:// 'Test.methodError -> error. Args: []. Res: Error {"name":"Error","message":"","stack":"some stack trace"}.' // Logs to the console before the method call:// 'Test.property1. Args: [].'test.property1// Logs to the console after the method call:// 'Test.property1 -> done. Args: []. Res: null.'
Configuration
Configuration object
Here's how the configuration object looks like:
(Live demo)
Hierarchical configThere're 3 layers of config:
- Global
- Class
- Method
Every time class-logger
logs a message all 3 of them are merged together.
Global config
You can set it using setConfig
function from class-logger
.
setConfig
Class config
You can set it using LogClass
decorator from class-logger
.
LogClass
Method config
You can set it using Log
decorator from class-logger
.
LogClass
Include
classInstance
It enables/disabled including the formatted class instance to your log messages. But what does 'formatted' really mean here? So if you decide to include it (remember, it's false
by default), default class formatter (ClassLoggerFormatterService
) is going to execute this sequence:
- Take own (non-prototype) properties of an instance.
- Why? It's a rare case when your prototype changes dynamically, therefore it hardly makes any sense to log it.
- Drop any of them that have
function
type.- Why? Most of the time
function
properties are just immutable arrow functions used instead of regular class methods to preservethis
context. It doesn't make much sense to bloat your logs with stringified bodies of those functions.
- Why? Most of the time
- Transform any of them that are not plain objects recursively.
- What objects are plain ones?
ClassLoggerFormatterService
considers an object a plain object if its prototype is strictly equal toObject.prototype
. - Why? Often we include instances of other classes as properties (inject them as dependencies). By stringifying them using the same algorithm we can see what we injected.
- What objects are plain ones?
- Stringify what's left.
Example:
// Logs to the console before the class' construction:// 'Test.construct. Args: []. Class instance: {"serviceA": ServiceA {},"prop1":42,"prop2":{"test":42}}.' // Logs to the console before the method call:// 'Test.method2. Args: []. Class instance: {"serviceA": ServiceA {},"prop1":42,"prop2":{"test":42}}.'test.method2// Logs to the console after the method call:// 'Test.method2 -> done. Args: []. Class instance: {"serviceA": ServiceA {},"prop1":42,"prop2":{"test":42}}. Res: 42.'
If a class instance is not available at the moment (e.g. for class construction or calls of static methods), it logs
N/A
.
Examples
Disable logging of arguments for all messages
Disable logging of arguments for end messages
Enable logging of a formatted class instance for all messages
Enable logging of a formatted class instance for end messages
Disable logging of class construction
Disable logging of method's return value (or thrown error)
Change logger
Which could look like this in real world:
setConfig
Formatting
You can pass your own custom formatter to the config to format messages to your liking.
Your custom formatter must be an object with properties start
and end
. It must comply with the following interface:
where IClassLoggerFormatterStartData
is:
and IClassLoggerFormatterEndData
is:
You can provide your own object with these two properties, but the easiest way to modify the formatting logic of class-logger
is to subclass the default formatter - ClassLoggerFormatterService
.
ClassLoggerFormatterService
has these protected
methods which are building blocks of final messages:
base
operation
args
classInstance
result
final
Generally speaking, start
method of ClassLoggerFormatterService
is base
+ args
+ classInstance
+ final
. end
is base
+ operation
+ args
+ classInstance
+ result
+ final
.
Examples
(Live demo)
Add timestampLet's take a look at how we could add a timestamp to the beginning of each message:
setConfig
FYI, winston, pino and pretty much any other logger are capable of adding timestamps on their own, so this example is purely educative. I'd advice to use your logger's built-in mechanism for creating timestamps if possible.