How to log all axios calls from one place in code

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.


Solution 1:

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[...]

Solution 2:

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.

Solution 3:

It looks like you can intercept all requests using an "interceptor", and log inside of it: https://github.com/mzabriskie/axios#interceptors

Solution 4:

You can try wrap the axios.request function in a Promise.

function loggedRequest(config) {
  return new Promise((resolve, reject) => {
    axios.request(config)
    .then((res) => {
      // log success, config, res here
      resolve(res);      
    })
    .catch(err => {
      // same, log whatever you want here
      reject(err);
    })
  })
}