npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@prague-digi/redux-logger

v1.0.7

Published

Logger for Redux

Downloads

8

Readme

@prague-digi/redux-logger

This is a forked version of the original redux-logger. It extends the default functionality with API reporting capabilities and exposes Logger for logging custom events.

API Reporting

To use the API reporting functionality, you need to specify reporting options when creating the redux middleware.

If you won't use the middleware, you need to first call Logger.init() with reporting options.

Logger API

The package exposes Logger to log custom events

import { Logger } from '@prague-digi/redux-logger'

init(options: Options)

Initialize the logger

debug(payload: Any)

Log debug level message

info(payload: Any)

Log info level message

warn(payload: Any)

Log warning message

error(payload: Any)

Log error message

log(payload: Any, level: LogLevel, type: LogType)

Log custom level/type message

Enums

The package also exposes LogType and LogLevel enums

LogType

import { LogType } from '@prague-digi/redux-logger'

console.log(LogType)
// ==> 
// {
//   REDUX: 'REDUX',
//   ERROR: 'ERROR',
//   CUSTOM: 'CUSTOM',
// };

LogLevel

import { LogLevel } from '@prague-digi/redux-logger'

console.log(LogLevel)
// ==> 
// {
//   DEBUG: 'debug',
//   INFO: 'info',
//   WARN: 'warn',
//   ERROR: 'error',
// };

Logger for Redux

npm npm Build Status

redux-logger

Table of contents

Install

npm i --save @prague-digi/redux-logger

Usage

import { applyMiddleware, createStore } from 'redux';

// Logger with default options
import logger from '@prague-digi/redux-logger'
const store = createStore(
  reducer,
  applyMiddleware(logger)
)

// Note passing middleware as the third argument requires redux@>=3.1.0

Or you can create your own logger with custom options:

import { applyMiddleware, createStore } from 'redux';
import { createLogger } from '@prague-digi/redux-logger'

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

const store = createStore(
  reducer,
  applyMiddleware(logger)
);

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

Options

{
  predicate, // if specified this function will be called before each action is processed with this middleware.
  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.
  duration = false: Boolean, // print the duration of each action?
  timestamp = true: Boolean, // print the timestamp with each action?

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

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

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

  diff = false: Boolean, // (alpha) show diff between states?
  diffPredicate // (alpha) filter function for showing states diff, similar to `predicate`,

  /**
   * Extended functionality by Moneta Digital
   */
  reporting: {
    postUrl: undefined: String // API endpoint to POST reports to
    interval: 5000: Number // Reporting interval in milliseconds,
    logTypes: []: Array, // Log types to report: ['redux', 'error', 'custom']. All types reported by default
    ignoredActions: ['@@redux-form/CHANGE']: Array // Action type names/patterns to ignore
  }
}

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

reporting (Object)

reporting.postUrl (String)

API endpoint to post reports to

Default: undefined

reporting.interval (Number)

Reporting interval in milliseconds

Default: 5000

reporting.logTypes (Array)

Log types to report. The package exposes these in

import { LogType } from '@prague-digi/redux-logger'

Default: ['redux', 'error', 'custom']

reporting.ignoredActions (Array)

Action type names/patterns to ignore. For example specifying 'redux-form' will ignore all action types containing 'redux-form' in their name.

Default: ['@@redux-form/CHANGE']

Recipes

Log only in development

const middlewares = [];

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

  middlewares.push(logger);
}

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

Log everything except actions with certain type

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

Collapse actions with certain type

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

Collapse actions that don't have errors

createLogger({
  collapsed: (getState, action, logEntry) => !logEntry.error
});

Transform Immutable (without combineReducers)

import { Iterable } from 'immutable';

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

const logger = createLogger({
  stateTransformer,
});

Transform Immutable (with combineReducers)

const logger = createLogger({
  stateTransformer: (state) => {
    let newState = {};

    for (var i of Object.keys(state)) {
      if (Immutable.Iterable.isIterable(state[i])) {
        newState[i] = state[i].toJS();
      } else {
        newState[i] = state[i];
      }
    };

    return newState;
  }
});

Log batched actions

Thanks to @smashercosmo

import { createLogger } from '@prague-digi/redux-logger';

const actionTransformer = action => {
  if (action.type === 'BATCHING_REDUCER.BATCH') {
    action.payload.type = action.payload.map(next => next.type).join(' => ');
    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
});

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