3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Axiosでrequest/responseの情報をログに出力

Last updated at Posted at 2020-03-30

Axiosのinterceptorsを使ったrequest/responseの情報をログに出力する場合のコード例です。
ログの部分をクラウドやログファイルへの出力に書き換えることで、request/responseの記録を残すことが可能です。

client.ts
const client = axios.create({
    baseURL: "https://xxx.yyy",
});

client.interceptors.request.use((config: AxiosRequestConfig) => {
    const url = `${config.baseURL}${config.url}`;
    console.log(`Method=${config.method} Url=${url} Body=${JSON.stringify(config.data)}`);
    return config;
});

client.interceptors.response.use(
    (response: AxiosResponse) => {
        const status = response.status;
        console.log(`Success: Status=${status}`);
        return response;
    },
    (error: AxiosError) => {
        const status = error.response!.status;
        const message = error.response!.data.messages[0] || "No message.";
        console.log(`Error: Status=${status} Message=${message}`);
        throw new HttpRequestError(status, message);
    }
);

実際のログでは日時とRequestIdを加えて以下のように出力しています。

2020-03-24 05:31:49 +0000 [716de8c0-78a6-4387-881c-17a2ca903f55]: Method=get Url=https://xxx.yyy/zzz Body=undefined
2020-03-24 05:31:49 +0000 [716de8c0-78a6-4387-881c-17a2ca903f55]: Error: Status=404 Message=xxx does not exist.
2020-03-24 05:31:49 +0000 [716de8c0-78a6-4387-881c-17a2ca903f55]: Method=get Url=https://xxx.yyy/zzz Body=undefined
2020-03-24 05:31:49 +0000 [716de8c0-78a6-4387-881c-17a2ca903f55]: Success: Status 200

より詳細な情報を出力したい場合はAxiosの型定義ファイルを参照してください。
出力したい情報が見つかるかもしれませんね。

index.d.ts
export interface AxiosResponse<T = any>  {
  data: T;
  status: number;
  statusText: string;
  headers: any;
  config: AxiosRequestConfig;
  request?: any;
}

export interface AxiosError<T = any> extends Error {
  config: AxiosRequestConfig;
  code?: string;
  request?: any;
  response?: AxiosResponse<T>;
  isAxiosError: boolean;
  toJSON: () => object;
}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?