Skip to content

Repository files navigation

RxJS Debug Operator 🐛



We've all had occasions where we've felt the need to simply pipe a tap(console.log) to our Observables to get some insight into what is occuring at a certain time.

This operator aims to reduce the amount of typing you'll have to do!

Usage

Installation

Install the package:
npm install rxjs-debug-operator

Adding it to your code

It's super simple to add and use:

Use your prefered import method:

import{debug}from'rxjs-debug-operator';// ORconst{ debug }=require('rxjs-debug-operator');

Then pipe it to your Observables:

constobs$=source.pipe(debug());

You can add a label to help identify the Observable:

constobs$=source.pipe(debug('My Observable'));// OUTPUT// My Observable {value}

It even allows you to turn it off if you are in a production environment, or for any other reason you wouldn't want to log to the console:

constobs$=source.pipe(debug({shouldIgnore: true}));

Examples

We can use it on its own to simply log out values to the console

constobs$=of('my test value');obs$.pipe(debug()).subscribe();// OUTPUT:// my test value

We can add a label to the logs:

constobs$=of('my test value');obs$.pipe(debug('Obserable A')).subscribe();// OUTPUT:// Obserable A my test value// We can label it using the config object syntax:constobs$=of('my test value');obs$.pipe(debug({label: 'Obserable A'})).subscribe();// OUTPUT:// Obserable A my test value// However, if we add a label and custom notification handlers,// we will not get the label in the logs by default:constobs$=of('my test value');obs$.pipe(debug({label: 'Obserable A',next: (value)=>console.log(value),})).subscribe();// OUTPUT:// my test value

We can also set up our own notification handlers if we prefer:

constobs$=of('my test value');obs$.pipe(debug({next: (value)=>console.log('my custom handler:',value)})).subscribe();// OUTPUT:// my custom handler: my test valueconstobs$=throwError('uh oh');obs$.pipe(debug({error: (value)=>console.log('my error handler:',value)})).subscribe();// OUTPUT:// my error handler: uh ohconstobs$=of('my test value');obs$.pipe(debug({complete: (value)=>console.log('I completed')})).subscribe();// OUTPUT:// I completed

We can access the default logger for more flexibility:

constobs$=of('my test value');obs$.pipe(debug((logger)=>({next: (v)=>logger.warn('Warning!',v),}))).subscribe();// OUTPUT// WARN: Warning! my test value

Setting Global Config

You can set some globals that make it more convenient to change:

  • the default logger
  • a global prefix to be appended to all logs
  • a global-level ignore flag

Change the Default Logger

You can change the default logger by creating an object that matches the DebugLogger interface, which can be seen below:

exportinterfaceDebugLogger{log: (...args: unknown[])=>void;error: (...args: unknown[])=>void;warn?: (...args: unknown[])=>void;debug?: (...args: unknown[])=>void;info?: (...args: unknown[])=>void;}

Once you have created your new logger, you can set it to be used as the default logger using setGlobalDebugConfig()

setGlobalDebugConfig({logger: myNewLogger,});

Now all your debug() operators will use your new logger to log the values it receives.

Adding a Global Prefix

You can also add a string prefix to all your logs at a global level, which can be useful to help identify logs.

setGlobalDebugConfig({prefix: 'My Prefix',});

Setting whether to ignore logging

You can also set whether all debug() should not log at the global level. This can be useful for turning it off in production environments.

setGlobalDebugConfig({shouldIgnore: isProduction,});

Example Winston Usage

import{DebugLogger,setGlobalDebugConfig}from'rxjs-debug-operator';constwinston=require('winston');constsysLogger=winston.createLogger({level: 'info',format: winston.format.json(),transports: [//// - Write all logs with level `error` and below to `error.log`// - Write all logs with level `info` and below to `combined.log`//newwinston.transports.File({filename: 'error.log',level: 'error'}),newwinston.transports.File({filename: 'combined.log'}),],});constdebugLogger: DebugLogger={log: (v)=>sysLogger.info(v),error: (e)=>sysLogger.error(e),};setGlobalDebugConfig({logger: debugLogger});constobs$=of('my test value');obs$.pipe(debug()).subscribe();// OUTPUT// 'my test value' written to `combined.log`

NOTES

It should be noted that local config options passed to the debug() operator will take precedence over any global values

API

Debug

debug(config?: Partial<DebugOperatorConfig>)

DebugOperatorConfig

See the list of options available to configure the operator below

OptionDescriptionTypeDefault
shouldIgnoreDo not perform the Debug actionsbooleanfalse
labelAdd a label to the logs to help identify the Observablestringnull
nextAction to perform when Observer receives a Next notification(value: T) => voidconsole.log
errorAction to perform when Observer receives an Error notification(value: unknown) => voidconsole.error
completeAction to perform when Observer receives a Completion notification() => void() => null

Global Debug Config

setGlobalDebugConfig(config: Partial<GlobalDebugConfig>)

GlobalDebugConfig

OptionDescriptionTypeDefault
shouldIgnoreDo not perform the Debug actionsbooleanfalse
prefixAdd a label to the logs to help identify the Observablestringnull
loggerLogger to use to log values recieved by debug()DebugLoggerconsole

DebugLogger

OptionDescriptionTypeDefault
logBasic log(...args: unknown[]) => voidconsole.log
errorError log(...args: unknown[]) => voidconsole.error
info?Info log(...args: unknown[]) => voidconsole.info
warn?Warn log(...args: unknown[]) => voidconsole.warn
debug?Debug log(...args: unknown[]) => voidconsole.debug

About

Debug operator to log observable values

Resources

Stars

21 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages