Skip to content

Instantly share code, notes, and snippets.

@dejanvasic85
Created September 23, 2020 00:28
Show Gist options
  • Save dejanvasic85/7c2d445d2fee57f4dd674f224c64cd2e to your computer and use it in GitHub Desktop.
Save dejanvasic85/7c2d445d2fee57f4dd674f224c64cd2e to your computer and use it in GitHub Desktop.
Axios Http Client with Logging
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import tracingLogger from '../../logging/tracingLogger';
interface RequestConfig extends AxiosRequestConfig {
metadata: {
startTime: number;
};
}
const createHttpClient = (baseURL: string, defaultHeaders: any = {}): AxiosInstance => {
const client = axios.create({
baseURL,
headers: { ...defaultHeaders, 'Cache-Control': 'no-cache' },
});
client.interceptors.request.use(
(config: RequestConfig) => {
const logger = tracingLogger();
logger.info({ url: config.url }, 'HttpClient Request starting');
config.metadata = { startTime: Date.now() };
return config;
},
(err) => Promise.reject(err),
);
client.interceptors.response.use(
(resp) => {
const config = resp.config as RequestConfig;
const latency = Date.now() - config.metadata.startTime;
const logger = tracingLogger();
logger.info({ url: config.url, latency, statusCode: resp.status }, 'HttpClient Request completed');
return resp;
},
(err) => Promise.reject(err),
);
return client;
};
export default createHttpClient;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment