Giter VIP home page Giter VIP logo

redux-sentry-middleware's Introduction

Build Status Latest Version Downloads per month

Sentry Middleware for Redux

Logs the type of each dispatched action to Sentry as "breadcrumbs" and attaches your last action and current Redux state as additional context.

It's a rewrite of raven-for-redux but with new Sentry unified APIs.

Installation

npm install --save redux-sentry-middleware

Usage

// store.js

import * as Sentry from "@sentry/browser"; 
// For usage with node 
// import * as Sentry from "@sentry/node";

import { createStore, applyMiddleware } from "redux";
import createSentryMiddleware from "redux-sentry-middleware";

import { reducer } from "./my_reducer";

Sentry.init({
  dsn: '<your dsn>'
});


export default createStore(
    reducer,
    applyMiddleware(
        // Middlewares, like `redux-thunk` that intercept or emit actions should
        // precede `redux-sentry-middleware`.
        createSentryMiddleware(Sentry, {
            // Optionally pass some options here.
        })
    )
);

API: createSentryMiddleware(Sentry, [options])

Arguments

  • Sentry (Sentry Object): A configured and "installed" [Sentry] object.
  • [options] (Object): See below for detailed documentation.

Options

While the default configuration should work for most use cases, middleware can be configured by providing an options object with any of the following optional keys.

breadcrumbDataFromAction (Function)

Default: action => undefined

Sentry allows you to attach additional context information to each breadcrumb in the form of a data object. breadcrumbDataFromAction allows you to specify a transform function which is passed the action object and returns a data object. Which will be logged to Sentry along with the breadcrumb.

Ideally we could log the entire content of each action. If we could, we could perfectly replay the user's entire session to see what went wrong.

However, the default implementation of this function returns undefined, which means no data is attached. This is because there are a few gotchas:

  • The data object must be "flat". In other words, each value of the object must be a string. The values may not be arrays or other objects.
  • Sentry limits the total size of your error report. If you send too much data, the error will not be recorded. If you are going to attach data to your breadcrumbs, be sure you understand the way it will affect the total size of your report.

Finally, be careful not to mutate your action within this function.

See the Sentry [Breadcrumb documentation].

actionTransformer (Function)

Default: action => action

In some cases your actions may be extremely large, or contain sensitive data. In those cases, you may want to transform your action before sending it to Sentry. This function allows you to do so. It is passed the last dispatched action object, and should return a serializable value.

Be careful not to mutate your action within this function.

If you have specified a [beforeSend] when you configured Sentry, note that actionTransformer will be applied before your specified beforeSend.

stateTransformer (Function)

Default: state => state

In some cases your state may be extremely large, or contain sensitive data. In those cases, you may want to transform your state before sending it to Sentry. This function allows you to do so. It is passed the current state object, and should return a serializable value.

Be careful not to mutate your state within this function.

If you have specified a [ beforeSend] when you configured Raven, note that stateTransformer will be applied before your specified beforeSend.

breadcrumbCategory (String)

Default: "redux-action"

Each breadcrumb is assigned a category. By default all action breadcrumbs are given the category "redux-action". If you would prefer a different category name, specify it here.

filterBreadcrumbActions (Function)

Default: action => true

If your app has certain actions that you do not want to send to Sentry, pass a filter function in this option. If the filter returns a truthy value, the action will be added as a breadcrumb, otherwise the action will be ignored. Note: even when the action has been filtered out, it may still be sent to Sentry as part of the extra data, if it was the last action before an error.

getUserContext (Optional Function)

Signature: state => userContext

Sentry allows you to associcate a [user context] with each error report. getUserContext allows you to define a mapping from your Redux state to the user context. When getUserContext is specified, the result of getUserContext will be used to derive the user context before sending an error report. Be careful not to mutate your state within this function.

If you have specified a [beforeSend] when you configured Raven, note that getUserContext will be applied before your specified beforeSend. When a getUserContext function is given, it will override any previously set user context.

getTags (Optional Function)

Signature: state => tags

Sentry allows you to associate [tags] with each report. getTags allows you to define a mapping from your Redux state to an object of tags (key โ†’ value). Be careful not to mutate your state within this function.

breadcrumbMessageFromAction (Function)

Default: action => action.type

breadcrumbMessageFromAction allows you to specify a transform function which is passed the action object and returns a string that will be used as the message of the breadcrumb.

By default breadcrumbMessageFromAction returns action.type.

Finally, be careful not to mutate your action within this function.

See the Sentry Breadcrumb documentation.

redux-sentry-middleware's People

Contributors

biomancer avatar captbaritone avatar dependabot[bot] avatar munrotom avatar vidit-sh avatar xnimorz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

redux-sentry-middleware's Issues

Usage with react native

Hi I'm trying to ship redux state breadcrumbs with react native. Breadcrumbs are being sent, but they all show up in Sentry as just POST http://localhost:8081/symbolicate [200]. Screenshot:

image

My store looks like:

import thunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';
import rootReducer from '../reducers';
import config from '../config/config';
import * as Sentry from '@sentry/react-native';
import createSentryMiddleware from "redux-sentry-middleware";

let middleware = [thunk];
let sentryUrl = config.sentry.projectUrl;

if (sentryUrl) {
  Sentry.init({
    dsn: sentryUrl
  });
  const middleware = [thunk, createSentryMiddleware(Sentry)];
} else {
  console.warn('config.sentry.projectUrl not set. Sentry not initialized.');
}

const initialState = {};

// rootReducer is the combined reducers
const store = createStore(rootReducer, initialState, composeWithDevTools(
  applyMiddleware(...middleware)
));

export default store;

We were using raven-for-redux, so trying to migrate to redux-sentry-middleware.

I'm testing on the iOS Simulator, so perhaps thats the issue.

[BUG] No issues being dispatched to Sentry

I'm currently migrating from raven-for-redux and I'm having some issues.

Initially I searched the Issues and found this. Follwing the threads instructions, I tried to move my setup into a separated sentry.js file which would be loaded first

import * as Sentry from '@sentry/browser';
Sentry.init({
  dsn: '<dsn>',
  beforeSend(event) {
    console.log('beforeSend', event);
    return event;
  }
});

export default Sentry;

Which is rendered in my top-level index.js

import React from 'react';
import ReactDOM from 'react-dom';
// import * as serviceWorker from './serviceWorker';
import './sentry';
import Root from './root';
ReactDOM.render(<Root />, document.getElementById('root'));

In my store.js file I have configured and injected the reporting middleware

import Sentry from '../../sentry';

Sentry.captureException(new Error('Sentry is working'));

const reportingMiddleware = createSentryMiddleware(Sentry, {
  // https://github.com/vidit-sh/redux-sentry-middleware#options
  stateTransformer: state => {
    // Don't include state in Sentry report
    console.log('[RM] stateTransformer');
    return undefined;
  },
  filterBreadcrumbActions: action => {
    // Only include "SENTRY_SEND" events, **AND POSSIBLY SOME PREAMBLE EVENTS**
    console.log('[RM] filterBreadcrumbActions');
    return true;
  },
  getUserContext: state => {
    // Add information about the User to the report
    const userContext = SentrySelector(state);
    console.log('[RM] getUserContext');
    return userContext;
  },
  breadcrumbDataFromAction: action => {
    console.log('[RM] breadcrumbDataFromAction');
    return action;
  },
  actionTransformer: action => {
    console.log('[RM] actionTransformer');
    return action;
  },
  // breadcrumbCategory: "redux-action"
  getTags: state => {
    console.log('[RM] getTags');
    return undefined;
  },
  breadcrumbMessageFromAction: action => {
    console.log('[RM] breadcrumbMessageFromAction');
    return action.type;
  }
});

// .....

let middlewares = [routerMiddleware, sagaMiddleware, reportingMiddleware];
const enhancer = composeEnhancers(applyMiddleware(...middlewares));

export default function configureStore(initialState = {}) {
  store = createInjectSagasStore(
    { defaultSagas: sagas },
    {
      ...reducers,
      router: connectRouter(history)
    },
    initialState,
    enhancer
  );
  return store;
}

In my console, I can see a single trigger of "beforeSend" for the manual invocation of Sentry Sentry.captureException(new Error('Sentry is working'));

I also see events for "filterBreadcrumbActions", "breadcrumbDataFromAction" and "breadcrumbMessageFromAction" but I never see any other events and nothing ever gets sent to sentry.

Please help me to understand what I'm doing incorrectly

redux state not serialised correctly

Hi there,
first of all, thank you for building this middleware.
I'm having an issue in which my redux state in not serialised correctly past the first level.
Any idea what I am missing?
Screen Shot 2020-02-19 at 9 26 46 am

Cannot see redux store in the additional data section in Sentry

import * as Sentry from '@sentry/browser';
import * as createSentryMiddleware from 'redux-sentry-middleware';
import { combineReducers, createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import reducers from './reducers';

export const store = createStore(
  reducers,
  composeWithDevTools(
    applyMiddleware(
      createSentryMiddleware(Sentry),
    ),
  ),
); 

Using typescript. Am I doing something wrong here in the setup?

Fails with sentry-expo 3.0

sentry-expo 3.0 is about to be released (current is 3.0.0-rc4). That release will include a breaking change wherein exports are now namespaced. That change leads to this package failing with sentry-expo 3.0:

IMG_FE9FF7B4E3C4-1

The fix is simple... instead of:

import * as Sentry from 'sentry-expo'

...

Sentry.captureException(error)

we now need to do:

import { Native as Sentry } from 'sentry-expo'

...

Sentry.captureException(error)

Please note that this applies to all/many methods, but does not apply to init.

I discovered this while tracking down changes required in order to upgrade a project to Expo SDK 39, which includes React 0.63, and therefore includes the change from YellowBox to LogBox. It seems that sentry-expo used YellowBox pre-3.0, and soon everyone using Expo is therefore going to upgrade that package to avoid YellowBox warnings. The relevant ticket is here: expo/expo#10300

Changelog

Hi @vidit-sh! Thank you for the project!

Between 0.1.3 and 0.1.8, can the changelog be filled in?

(I assume they were just security package pinnings?)

Changelog / Release notes?

Hi, thank you for the project @vidit-sh!

Do we want to keep a CHANGES.md file or add a list of changes to github releases?

(Was wondering what changed between versions, sometimes git logs work, but it's
helpful to know why the maintainer(s) decided to make the release in their own words
and what happened in between)

Never accept notifications from sentry.

Sentry.configureScope(scope => {
scope.addEventProcessor((event, hint) => {
const state = store.getState();
event.extra = {
...event.extra,
lastAction: actionTransformer(lastAction),
state: stateTransformer(state)
};
if (getUserContext) {
event.user = { ...event.user, ...getUserContext(state) };
}
if (getTags) {
const tags = getTags(state);
Object.keys(tags).forEach(key => {
scope.tags = { ...scope.tags, [key]: tags[key] };
});
}
return event;
});
});

The event processor created when creating redux sentry middleware has never been executed.

Do I need to configure some other things or Upgrade Redux?

https://github.com/getsentry/sentry-javascript/blob/1fb4808e69dd272c951c86fa90570c04ccfbad6b/packages/hub/src/scope.ts#L68-L81

I don't know if it is this reason:
if the last processor return null, it will not to be executed.

And why not to manage scope in middleware?

function createSentryMiddleware(hub, options = {}) {
  const {
    breadcrumbDataFromAction = identity,
    actionTransformer = identity,
    stateTransformer = identity,
    breadcrumbCategory = 'redux-action',
    filterBreadcrumbActions = filter,
    getUserContext,
    getTags,
  } = options;

  return store => {
    let lastAction;

    return next => action => {
      Sentry.configureScope(scope => {
        const state = store.getState();
        scope.setExtra('state', stateTransformer(state));
        scope.setExtra('lastAction', actionTransformer(lastAction));
        if (getUserContext) {
          scope.setUser({
            ...scope.user,
            ...getUserContext(state),
          });
        }
        if (getTags) {
          Object.entries(getTags(state)).forEach(item => {
            scope.setTag(...item);
          });
        }
      });
      if (filterBreadcrumbActions(action)) {
        Sentry.addBreadcrumb({
          category: breadcrumbCategory,
          message: action.type,
          level: 'info',
          data: breadcrumbDataFromAction(action),
        });
      }

      lastAction = action;
      return next(action);
    };
  };
}

Version Info:

  • Redux: 3.7.2
  • redux-sentry-middleware: 0.0.12
  • @sentry/browser: 4.4.2

Add a callback?

Would love the ability to add a callback to execute after the error has been sent to sentry.

In my case, I have middleware = [myErrorCatchingMiddleware, Thunk, reduxSentryMiddleWare]. The function of "myErrorCatchingMiddleware" is to dispatch an update to the store to notify that an uncaught error has occurred, then re-throws the error to be caught again by reduxSentryMiddleware.

The result of this is that the last dispatched action as shown in Sentry is a result of myErrorCatchingMiddleware, as opposed to the actual action that caused the issue.

Thanks for the great module :)

Do I have to re-init Sentry?

I have Sentry.init() in my index.js. Do I have to re-init Sentry in my store.js where I appy the createSentryMiddleware()? or can I just pass the imported sentry (import * as Sentry from "@sentry/browser";)

currently my store.js looks like this (while I do see the fired actions in sentry I get no user context):

import { applyMiddleware, createStore, combineReducers, compose } from "redux";
import * as Sentry from "@sentry/browser";
import reduxPromiseMiddleware from "redux-promise-middleware";
import createSentryMiddleware from "redux-sentry-middleware";

import * as reducers from "./ducks";

// only needed for redux dev tools
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const rootReducer = combineReducers(reducers);
const middleware = composeEnhancers(
  applyMiddleware(
    reduxPromiseMiddleware(),
    createSentryMiddleware(Sentry, {
      getUserContext: state => state.user.user
    })
  )
);

export default createStore(rootReducer, middleware);

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.