GithubHelp home page GithubHelp logo

gaearon / redux-logger Goto Github PK

View Code? Open in Web Editor NEW

This project forked from logrocket/redux-logger

2.0 2.0 1.0 400 KB

Logger middleware for redux

Home Page: http://fcomb.github.io/redux-logger/

License: MIT License

JavaScript 94.03% HTML 5.56% CSS 0.41%

redux-logger's Introduction

Logger for Redux

Build Status

redux-logger

Install

npm i --save redux-logger

Usage

import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import promise from 'redux-promise';
import createLogger from 'redux-logger';

const logger = createLogger();
const createStoreWithMiddleware = applyMiddleware(thunk, promise, logger)(createStore);
const store = createStoreWithMiddleware(reducer);

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

API

redux-logger exposes single constructor function for creating logger middleware.

createLogger(options?: Object) => LoggerMiddleware

Options

level (String)

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

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: window.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) => 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: Function) => 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

Recipes

log only in dev mode

import thunk from 'redux-thunk';

const middlewares = [thunk];

if (process.env.NODE_ENV === `development`) {
  const createLogger = require(`redux-logger`);
  const logger = createLogger();
  middlewares.push(logger);
}

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

log everything except actions with type AUTH_REMOVE_TOKEN

createLogger({
  predicate: (getState, action) => action.type !== AUTH_REMOVE_TOKEN
});

collapse actions with type FORM_CHANGE

createLogger({
  collapsed: (getState, action) => action.type === FORM_CHANGE
});

transform Immutable objects into JSON

import {Iterable} from 'immutable';

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

const logger = createLogger({
  stateTransformer,
});

log batched actions

Thanks to @smashercosmo

import createLogger from 'redux-logger';

const actionTransformer = action => {
  if (action.type === 'BATCHING_REDUCER.BATCH') {
    action.payload.type = action.payload.reduce((result, next) => {
      const prefix = result ? result + ' => ' : '';
      return prefix + next.type;
    }, '');

    return action.payload;
  }

  return action;
};

const level = 'info';

const logger = {};

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

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

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

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

export default createLogger({
  level,
  actionTransformer,
  logger
});

License

MIT

redux-logger's People

Contributors

af avatar brandonlilly avatar cappslock avatar danez avatar dreampulse avatar ericelliott avatar esamattis avatar farin avatar greenkeeperio-bot avatar grushetsky avatar idolize avatar ilyapomaskin avatar jhsu avatar kevinold avatar matthewmueller avatar steida avatar vkrol avatar vovacodes avatar webpro avatar weltenwort avatar yoo2001818 avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

Forkers

rubythonode

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.