Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log all axios calls from one place in code

Tags:

axios

I am using axios for a react application and I would like to log all axios calls that I'm making anywhere in the app. I'm already using a single global instance of axios via the create function and I am able to log a generic console.log. However I would like more info like function being called, parameters, etc.

like image 585
David Choi Avatar asked Jan 19 '17 20:01

David Choi


People also ask

How do I do multiple Axios requests?

Since axios returns a Promise we can go for multiple requests by using Promise. all , luckily axios itself also ships with a function called all , so let us use that instead and add two more requests. Again we define the different URLs we want to access. const requestOne = axios.

Which method is used to make multiple concurrent requests using Axios?

all is a helper method built into Axios to deal with concurrent requests. Instead of making multiple HTTP requests individually, the axios. all method allows us to make multiple HTTP requests to our endpoints altogether.


2 Answers

The best way to do this would be an interceptor. Each interceptor is called before a request/response. In this case a logging interceptor would be.

axios.interceptors.request.use(request => {
  console.log('Starting Request', JSON.stringify(request, null, 2))
  return request
})

axios.interceptors.response.use(response => {
  console.log('Response:', JSON.stringify(response, null, 2))
  return response
})

or something to that effect.

It's good that you're using a new instance of axios:

const api = axios.create({
  timeout: 1000
})

That way you can call

api.interceptors[...]
like image 158
Kevin Velasco Avatar answered Oct 17 '22 12:10

Kevin Velasco


Use axios-debug-log

  1. npm install --save axios-debug-log
  2. require('axios-debug-log') before any axios call
  3. Set the environment variable DEBUG=axios

By default, you'll see logs like the following:

  axios POST /api/auth/login +0ms
  axios 200  (POST http://localhost:8080/api/auth/login) +125ms
  axios POST /api/foo +0ms
  axios 200  (POST http://localhost:8080/api/foo) +15ms

Refer to the docs for configuration and customization options.

like image 25
Dheeraj Vepakomma Avatar answered Oct 17 '22 13:10

Dheeraj Vepakomma