Redux Logger

Logger for Redux

README

Logger for Redux npm npm Build Status


redux-logger

Now maintained by LogRocket!
undefined

LogRocket is a production Redux logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay Redux actions + state, network requests, console logs, and see a video of what the user saw.


For more informatiom about the future of redux-logger, check out the discussion here.

Table of contents

  [Transform Immutable (without combineReducers)](#transform-immutable-without-combinereducers)
  [Transform Immutable (with combineReducers)](#transform-immutable-with-combinereducers)
Known issues (withreact-native only at this moment)

Install

npm i --save redux-logger

Typescript types are also available, via DefinitelyTyped:

npm i @types/redux-logger

Usage

  1. ``` js
  2. import { applyMiddleware, createStore } from 'redux';

  3. // Logger with default options
  4. import logger from 'redux-logger'
  5. const store = createStore(
  6.   reducer,
  7.   applyMiddleware(logger)
  8. )

  9. // Note passing middleware as the third argument requires redux@>=3.1.0
  10. ```

Or you can create your own logger with custom options:
  1. ``` js
  2. import { applyMiddleware, createStore } from 'redux';
  3. import { createLogger } from 'redux-logger'

  4. const logger = createLogger({
  5.   // ...options
  6. });

  7. const store = createStore(
  8.   reducer,
  9.   applyMiddleware(logger)
  10. );
  11. ```

Note: logger must be the last middleware in chain, otherwise it will log thunk and promise, not actual actions (#20).

Options

  1. ``` js
  2. {
  3.   predicate, // if specified this function will be called before each action is processed with this middleware.
  4.   collapsed, // takes a Boolean or optionally a Function that receives `getState` function for accessing current store state and `action` object as parameters. Returns `true` if the log group should be collapsed, `false` otherwise.
  5.   duration = false: Boolean, // print the duration of each action?
  6.   timestamp = true: Boolean, // print the timestamp with each action?

  7.   level = 'log': 'log' | 'console' | 'warn' | 'error' | 'info', // console's level
  8.   colors: ColorsObject, // colors for title, prev state, action and next state: https://github.com/LogRocket/redux-logger/blob/master/src/defaults.js#L12-L18
  9.   titleFormatter, // Format the title used when logging actions.

  10.   stateTransformer, // Transform state before print. Eg. convert Immutable object to plain JSON.
  11.   actionTransformer, // Transform action before print. Eg. convert Immutable object to plain JSON.
  12.   errorTransformer, // Transform error before print. Eg. convert Immutable object to plain JSON.

  13.   logger = console: LoggerObject, // implementation of the `console` API.
  14.   logErrors = true: Boolean, // should the logger catch, log, and re-throw errors?

  15.   diff = false: Boolean, // (alpha) show diff between states?
  16.   diffPredicate // (alpha) filter function for showing states diff, similar to `predicate`
  17. }
  18. ```

Options description


__level (String | Function | Object)__

Level of console. warn, error, info or else.

It can be a function (action: Object) => level: String.

It can be an object with level string for: prevState, action, nextState, error

It can be an object with getter functions: prevState, action, nextState, error. Useful if you want to print
message based on specific state or action. Set any of them to false if you want to hide it.

prevState(prevState: Object) => level: String
action(action: Object) => level: String
nextState(nextState: Object) => level: String
error(error: Any, prevState: Object) => level: String

Default: log

__duration (Boolean)__

Print duration of each action?

Default: false

__timestamp (Boolean)__

Print timestamp with each action?

Default: true

__colors (Object)__

Object with color getter functions: title, prevState, action, nextState, error. Useful if you want to paint
message based on specific state or action. Set any of them to false if you want to show plain message without colors.

title(action: Object) => color: String
prevState(prevState: Object) => color: String
action(action: Object) => color: String
nextState(nextState: Object) => color: String
error(error: Any, prevState: Object) => color: String

__logger (Object)__

Implementation of the console API. Useful if you are using a custom, wrapped version of console.

Default: console

__logErrors (Boolean)__

Should the logger catch, log, and re-throw errors? This makes it clear which action triggered the error but makes "break
on error" in dev tools harder to use, as it breaks on re-throw rather than the original throw location.

Default: true

__collapsed = (getState: Function, action: Object, logEntry: Object) => Boolean__

Takes a boolean or optionally a function that receives getState function for accessing current store state and action object as parameters. Returns true if the log group should be collapsed, false otherwise.

Default: false

__predicate = (getState: Function, action: Object) => Boolean__

If specified this function will be called before each action is processed with this middleware.
Receives getState function for  accessing current store state and action object as parameters. Returns true if action should be logged, false otherwise.

Default: null (always log)

__stateTransformer = (state: Object) => state__

Transform state before print. Eg. convert Immutable object to plain JSON.

Default: identity function

__actionTransformer = (action: Object) => action__

Transform action before print. Eg. convert Immutable object to plain JSON.

Default: identity function

__errorTransformer = (error: Any) => error__

Transform error before print.

Default: identity function

__titleFormatter = (action: Object, time: String?, took: Number?) => title__

Format the title used for each action.

Default: prints something like action @ ${time} ${action.type} (in ${took.toFixed(2)} ms)

__diff (Boolean)__

Show states diff.

Default: false

__diffPredicate = (getState: Function, action: Object) => Boolean__

Filter states diff for certain cases.

Default: undefined

Recipes

Log only in development

  1. ``` js
  2. const middlewares = [];

  3. if (process.env.NODE_ENV === `development`) {
  4.   const { logger } = require(`redux-logger`);

  5.   middlewares.push(logger);
  6. }

  7. const store = compose(applyMiddleware(...middlewares))(createStore)(reducer);
  8. ```

Log everything except actions with certain type

  1. ``` js
  2. createLogger({
  3.   predicate: (getState, action) => action.type !== AUTH_REMOVE_TOKEN
  4. });
  5. ```

Collapse actions with certain type

  1. ``` js
  2. createLogger({
  3.   collapsed: (getState, action) => action.type === FORM_CHANGE
  4. });
  5. ```

Collapse actions that don't have errors

  1. ``` js
  2. createLogger({
  3.   collapsed: (getState, action, logEntry) => !logEntry.error
  4. });
  5. ```

Transform Immutable (without combineReducers)

  1. ``` js
  2. import { Iterable } from 'immutable';

  3. const stateTransformer = (state) => {
  4.   if (Iterable.isIterable(state)) return state.toJS();
  5.   else return state;
  6. };

  7. const logger = createLogger({
  8.   stateTransformer,
  9. });
  10. ```

Transform Immutable (with combineReducers)

  1. ``` js
  2. const logger = createLogger({
  3.   stateTransformer: (state) => {
  4.     let newState = {};

  5.     for (var i of Object.keys(state)) {
  6.       if (Immutable.Iterable.isIterable(state[i])) {
  7.         newState[i] = state[i].toJS();
  8.       } else {
  9.         newState[i] = state[i];
  10.       }
  11.     };

  12.     return newState;
  13.   }
  14. });
  15. ```

Log batched actions

Thanks to @smashercosmo
  1. ``` js
  2. import { createLogger } from 'redux-logger';

  3. const actionTransformer = action => {
  4.   if (action.type === 'BATCHING_REDUCER.BATCH') {
  5.     action.payload.type = action.payload.map(next => next.type).join(' => ');
  6.     return action.payload;
  7.   }

  8.   return action;
  9. };

  10. const level = 'info';

  11. const logger = {};

  12. for (const method in console) {
  13.   if (typeof console[method] === 'function') {
  14.     logger[method] = console[method].bind(console);
  15.   }
  16. }

  17. logger[level] = function levelFn(...args) {
  18.   const lastArg = args.pop();

  19.   if (Array.isArray(lastArg)) {
  20.     return lastArg.forEach(item => {
  21.       console[level].apply(console, [...args, item]);
  22.     });
  23.   }

  24.   console[level].apply(console, arguments);
  25. };

  26. export default createLogger({
  27.   level,
  28.   actionTransformer,
  29.   logger
  30. });
  31. ```

To Do

- [x] Update eslint config to airbnb's
- [ ] Clean up code, because it's very messy, to be honest
- [ ] Write tests
- [ ] Node.js support
- [ ] React-native support

Feel free to create PR for any of those tasks!

Known issues

Performance issues in react-native (#32)

License

MIT