Giter Site home page Giter Site logo

alexbrazier / react-native-network-logger Goto Github PK

View Code? Open in Web Editor NEW
482.0 10.0 41.0 7.67 MB

An HTTP network request monitor for React Native with in-app interface for iOS and Android with no native code

License: MIT License

TypeScript 97.60% JavaScript 2.40%
react-native ios android network debugger logging network-monitoring charles network-debug hacktoberfest

react-native-network-logger's Introduction

react-native-network-logger GitHub stars

CI Dependencies npm npm bundle size npm downloads License

An HTTP traffic monitor for React Native including in app interface.

An alternative to Wormholy but for both iOS and Android and with zero native dependencies.

If this project has helped you out, please support us with a star ๐ŸŒŸ.

Features

  • Log networks requests on iOS and Android
  • View network requests made with in app viewer
  • Debug network requests on release builds
  • Individually view request/response headers and body
  • Copy or share headers, body or full request
  • Share cURL representation of request
  • Zero native or JavaScript dependencies
  • Built in TypeScript definitions
  • Extracts GraphQL operation name
  • Export all logs in HAR format

Screenshots

iOS

Android

Setup

Install

yarn add react-native-network-logger

or

npm install --save react-native-network-logger

Start Logging

Call startNetworkLogging in your apps entry point to log every request, or call it on a button press to manually trigger it.

import { startNetworkLogging } from 'react-native-network-logger';

startNetworkLogging();
AppRegistry.registerComponent('App', () => App);

Display Requests and Responses

import NetworkLogger from 'react-native-network-logger';

const MyScreen = () => <NetworkLogger />;

Themes

You can change between the dark and light theme by passing the theme prop with "dark" or "light".

import NetworkLogger from 'react-native-network-logger';

const MyScreen = () => <NetworkLogger theme="dark" />;

If preferred you can also override the theme entirely by passing in a theme object.

Note: breaking theme changes are not guaranteed to follow semver for updates

import NetworkLogger from 'react-native-network-logger';

const MyScreen = () => (
  <NetworkLogger
    theme={{
      colors: {
        background: 'red',
      },
    }}
  />
);

Logging options

Max Requests

You can configure the max number of requests stored on the device using by calling startNetworkLogging with the maxRequests option. The default is 500.

startNetworkLogging({ maxRequests: 500 });

Ignored Hosts

You can configure hosts that should be ignored by calling startNetworkLogging with the ignoredHosts option.

startNetworkLogging({ ignoredHosts: ['test.example.com'] });

Ignored Urls

You can configure urls that should be ignored by calling startNetworkLogging with the ignoredUrls option.

startNetworkLogging({ ignoredUrls: ['https://test.example.com/page'] });

Ignored Patterns

You can configure url patterns, including methods that should be ignored by calling startNetworkLogging with the ignoredPatterns option.

startNetworkLogging({
  ignoredPatterns: [/^GET http:\/\/test\.example\.com\/pages\/.*$/],
});

The pattern to match with is the method followed by the url, e.g. GET http://example.com/test so you can use the pattern to match anything, e.g. ignoring all HEAD requests.

startNetworkLogging({
  // Ignore all HEAD requests
  ignoredPatterns: [/^HEAD /],
});

Sorting

Set the sort order of requests. Options are asc or desc, default is desc (most recent at the top).

import NetworkLogger from 'react-native-network-logger';

const MyScreen = () => <NetworkLogger sort="asc" />;

Max Rows

Set the maximum number of rows to display in the list to improve rendering. Default is same as request limit.

import NetworkLogger from 'react-native-network-logger';

const MyScreen = () => <NetworkLogger maxRows={100} />;

Compact Rows

Make the rows smaller to fit more on the screen.

import NetworkLogger from 'react-native-network-logger';

const MyScreen = () => <NetworkLogger compact />;

Force Enable

If you are running another network logging interceptor, e.g. Reactotron, the logger will not start as only one can be run at once. You can override this behaviour and force the logger to start by using the forceEnable option.

startNetworkLogging({ forceEnable: true });

Integrate with existing navigation

Use your existing back button (e.g. in your navigation header) to navigate within the network logger.

import NetworkLogger, { getBackHandler } from 'react-native-network-logger';

const navigation = useNavigation();
const onBack = getBackHandler(navigation.goBack);

const MyScreen = () => (
  <Screen onBackPressed={onBack}>
    <NetworkLogger />
  </Screen>
);

Example App

To test the example app, after cloning the repo, install the required dependencies by running:

yarn bootstrap

Then start the example app by running:

yarn example start

You should then be able to open the expo server at http://localhost:3000/ and launch the app on iOS or Android.

For more setup and development details, see Contributing.

Why

Network requests can be debugged using tools such as React Native Debugger, however this requires both a debug build of the app and the debugger to be enabled. This library can be built with you app and usable by anyone using your app to see network issues and report them back to developers.

As the library is very small you can safely bundle it with the production version of your app and put it behind a flag, or have a separate testing build of the app which has the network logger enabled.

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests.

License

This project is licensed under the MIT License - see the LICENSE file for details.

react-native-network-logger's People

Contributors

alexbrazier avatar chrisbruford avatar dependabot[bot] avatar jwallet avatar lukmccall avatar spencer-yoder avatar ximxim 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-network-logger's Issues

Single Request not showing as pending

Describe the bug

When only one request is made at a time, it does not show up a pending, and will only be added to the list after it completes.
If more then one API request is created at the same time, then the pending API request will show as pending.

Expected behavior

When only 1 API request is fired, then it should show up in the request list as pending. Once the request is completed the status number and time should be updated.

Screenshots

It was easier for me to post videos on my fork and screenshots

Working as expected: https://github.com/Spencer-Yoder/react-native-network-logger/blob/Git-issue/Two%20Request(Working%20as%20expected).mp4
Defect: https://github.com/Spencer-Yoder/react-native-network-logger/blob/Git-issue/Single%20Request(Defect).mp4

Platform:

  • iOS - I have not tested on iOS
  • Android - Tested on Emulator and Physical Device

Additional context

Checked out master at v1.7.0 and ran the example project
It is easy to recreate it for me, if there is a delay in the request. Using https://postman-echo.com/delay/5 worked for me.

Not working on Axios

I am using Axios for network call and using router-flux for the navigation.
I have followed all the steps from README

import { startNetworkLogging } from 'react-native-network-logger';

startNetworkLogging();
AppRegistry.registerComponent(appName, () => App);
            <Scene
              key="networkLogger"
              component={() => <NetworkLogger theme={'dark'} />}
              back
              headerLayoutPreset="center"
              renderTitle={() => <PlainTitleBar />}
            />
      Actions.networkLogger({
        onBack: () => { Actions.pop() }
      });

But no request or response was shown. I have tested it using the simulator, also on a real devices with both debug and release variants. Is there any config that I missed? Thanks

Screen Shot 2021-08-23 at 16 34 13

Does not work with Pinch

Describe the bug
Network Calls made by Pinch not showing the log.

Platform:

  • [x ] iOS
  • [x ] Android

Web support?

Feature Request

Web browsers have a network logger. The only thing that this library should do is "Nothing"!
When i use this library with react-native-web,i got this error:

Failed to compile.
/Users/xxx/xxx/xxx/node_modules/react-native/Libraries/Network/XMLHttpRequest.js
Module not found: Can't resolve './RCTNetworking' in '/Users/xxx/xxx/SellerCenterApp/node_modules/react-native/Libraries/Network'

I finally solve this error by DELETE all references of this library when i am building for the web.

Additional context

On the web platform, this library should do nothing, because the browsers have their logging already.

Response Body not rendering

Describe the bug

  • When launching the network debug and clicking onto a request, it does not show the response body even though the request was successful.
  • However, it does show a large chunk of space where the response would have been.

Expected behavior

  • Should show the response body

Screenshots
Screen Shot 2020-06-25 at 9 04 58 pm

Platform:

  • iOS
  • Android

Additional context

Network recording starts automatically?

Describe the bug

I noticed in the example app that startNetworkLogging never gets called. I traced this down to the useEffect hook to the UI component that starts it. So if at any time the UI component was rendered when it shouldn't be, then all network traffic in the session would be recorded.

logger.enableXHRInterception();

Judging by the readme this is not expected.

Is this a Bug and should this line be deleted?

Expected behavior

Screenshots

Platform:

  • iOS
  • Android

Additional context

FormData in POST requests crash app

Describe the bug
If there is a request that contains FormData in the body, navigating to the details section of that request crashes the app.

Expected behavior
FormData should be parsed correctly and displayed to the user.

Screenshots
image

Platform:

  • iOS
  • Android

Additional context
I believe the issue lies in this method that's inside NetworkRequestInfo.ts:

  private stringifyFormat(data: string) {
    try {
      return JSON.stringify(JSON.parse(data), null, '\t');
    } catch (e) {
      return data;
    }
  }

JSON.parse throws an error, it's caught, then the FormData is passed onto <LargeText> as a child but since it's an object still, it crashes

Error: Text strings must be rendered within a <Text> component.

When tapping on a specific request in the list view I am unable to view the details. I receive the following error message:

Error: Text strings must be rendered within a <Text> component.

This is in a fairly new app using RN 0.62.2

Looking at the code in Header.tsx it seems it's rendering children into a <Text> element. Not exactly sure what's in children but that seems to be where the error occurs.

Screenshots
Screen Shot 2020-06-24 at 12 04 11 PM

Platform:

  • iOS
  • Android

Close button content overlap

Hi, excellent job!

Just one small UI thing noticed:
Close button is overlap with request url.
I think having close button in same header row as more would be better.

image

Having a small problem importing package

When I try importing your package into my currently existing react-native project I get a problem from the package saying in the import part there is a syntax error with an unexpected token. All I did was yarn add react-native-network-logger then tried running my project again. Thank you for any help! I have attached an image of the error message.
Screen Shot 2020-07-10 at 3 04 10 PM

Save and share api requests

Feature Request

Add feature to export/copy api request information from the monitor screen so it can be sent to others via email or slack etc.

The response body is in the `Loading...` state

Describe the bug
The response body is in the Loading... state

Expected behavior
I should see the body response

Screenshots
image

Platform:

  • iOS
  • Android (not tested)

Additional context
react-native-network-logger: v1.14.0
react-native: v0.71.3

was working on the previous react-native version v0.69.5

Change sorting order

Feature Request
It should be possible to sort requests by most recent at the top or most recent at the bottom depending on the users preference.

Friendlier response body section

Feature Request
Make response body section more user friendly. Mobile screen is limited and let say the response is very big, then it could hurt UX when inspecting. We can collapse the JSON value like redux-devtools.

There is also react-native-json-tree which is based on react-json-tree used by redux-devtools.

Thanks!

Additional context

  const getFullRequest = () => {
    const processedRequest = {
      ...request,
      response: responseBody ? JSON.parse(responseBody) : undefined,
      duration: request.duration,
    };
    return JSON.stringify(processedRequest, null, 2);
  };

Export all Logs

Feature Request

Having the ability to export the full list of logged request to a JSON file stored locally on the device.

I know the project right now doesn't have any dependencies (that's really nice), but the easiest and most practical way to do it would include using a package like react-native-fs.

Additional context

stuck at pending state

I'm using Axios. Logs are stuck at pending state also it is only showing response and request headers not the body of the request.
In reactron I'm able to see logs properly

Screenshot_1615275118

Conflict with `reactotron-react-native` library

Hi! First of all, awesome work on this library, it is amazing.

Well, I open this issue using the "Other" template because I really don't know if the problem that I found has some workaround.

As you can see in the image below, at this point in code, the library checks if the interceptor is enabled or not, and if it is already enabled, the code just returns:

image

So after debugging, I just check that the reactotron-react-native library was enabling that by default, just by importing the library, and that was making the Logger skip the setup and because of that do not log any request.

What I did was remove the Reactotron and put it again manually just when I want to debug other things in my application.

So, I was wondering if there's any way to work around this conflict between these two libraries and make them work together.

Thanks!

is there a way of tracking request made by webviews?

Hey! I hope you are doing well!
This library only tracks requests that are made by the app, right? For example, if I develop a web with React and I render it in a webview in my RN app, am I able to see the requests made by that web page?

Changed `ignoredHosts` to `ignoredPatterns`

Feature Request
I want to filter out the /ping calls from the server done by NetInfo but they're in the same host as my main server that I am trying to monitor.

If we say the request has the following text

HEAD https://trajano.net/ping

It would simplify us by having rules that look like

ignoredPatterns: [
  /^HEAD https:\/\/trajano.net\/ping$/
]

Additional context

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.