Skip to content

Commit

Permalink
Add debug logging to Axios requests
Browse files Browse the repository at this point in the history
  • Loading branch information
martin-helmich committed May 13, 2024
1 parent 56ae5c9 commit b781ec3
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/BaseCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { MittwaldAPIV2Client } from "@mittwald/api-client";
import { configureAxiosRetry } from "./lib/api_retry.js";
import { configureConsistencyHandling } from "./lib/api_consistency.js";
import { getTokenFilename, readApiToken } from "./lib/auth/token.js";
import { configureAxiosLogging } from "./lib/api_logging.js";

export abstract class BaseCommand extends Command {
protected authenticationRequired = true;
Expand All @@ -23,6 +24,7 @@ export abstract class BaseCommand extends Command {
this.apiClient.axios.defaults.headers["User-Agent"] =
`mittwald-cli/${this.config.version}`;

configureAxiosLogging(this.apiClient.axios);
configureAxiosRetry(this.apiClient.axios);
configureConsistencyHandling(this.apiClient.axios);
}
Expand Down
35 changes: 35 additions & 0 deletions src/lib/api_logging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import debug from "debug";
import { AxiosInstance } from "@mittwald/api-client-commons";

/**
* Configure logging for Axios requests and responses using the `debug` module.
*
* Run the CLI with `DEBUG=mw:api:client:*` to see the logs. Keep in mind that
* this will also log sensitive information in request bodies or headers.
*/
export function configureAxiosLogging(axios: AxiosInstance) {
const baseDebugger = debug("mw:api:client");
const reqDebugger = baseDebugger.extend("request");
const resDebugger = baseDebugger.extend("response");

axios.interceptors.request.use((config) => {
reqDebugger(
"%s %s requested with %O",
config.method?.toUpperCase(),
config.url,
config.data,
);
return config;
});

axios.interceptors.response.use((response) => {
resDebugger(
"%s %s responded with %o %O",
response.config.method?.toUpperCase(),
response.config.url,
response.status + " " + response.statusText,
response.data,
);
return response;
});
}

0 comments on commit b781ec3

Please sign in to comment.