Axios interceptors for automatic HTTP request/response/error logging to console & files
npm install awesome-axios-logger







Axios interceptors for automatic HTTP request/response/error logging to files

š Modern: Built with ESM6 modules and TypeScript
šŖ¶ Lightweight: Tree-shakable, minimal bundle size
šŖ Type-safe: Full TypeScript support with comprehensive type definitions
ā” Fast: Non-blocking async file logging
šÆ Focused: Request, response, and error logging without bloat
š¦ Zero Dependencies: No extra runtime dependencies ā works out of the box with just axios and this package.
``ts
import axios from 'axios';
import { attachLogger } from 'awesome-axios-logger';
const client = axios.create({ baseURL: 'https://api.example.com' });
attachLogger(client, { dir: './logs' });
await client.get('/v1/player');
`
- Automatic file logging of HTTP requests, responses, and errors
- Smart content detection (JSON, HTML, plain text)
- Customizable filename patterns
- Per-request logging control (skipLog, logAs)@lsk4/log
- Console output via (pino-style)
- Zero config ā just specify a directory
`bash`
npm install axios awesome-axios-logger
`typescript`
import { attachLogger, createLoggerInterceptors } from 'awesome-axios-logger';
`typescript
import axios from 'axios';
import { attachLogger } from 'awesome-axios-logger';
const client = axios.create({
baseURL: 'https://api.example.com',
});
// Attach logger ā all requests will be logged to ./logs
attachLogger(client, {
dir: './logs',
});
// Make requests as usual
await client.get('/v1/player');
await client.post('/v1/submit', { data: 'hello' });
// Skip logging for specific requests
await client.get('/health', { skipLog: true });
// Custom name in logs
await client.get('/v1/get_user_info', { logAs: 'user' });
`
Uses @lsk4/log ā a JSON-compatible logger (pino-style).
Enable logs via environment variable:
`bash`
DEBUG=axios node app.js
Example output:
``
[axios] -> GET v1_player (124B)
[axios] <- v1_player 200 json (45.2KB) 234ms
On error:
``
[axios] -> POST submit (1.2KB)
[axios] <- submit 500 json (156B) 89ms
``
logs/
āāā 1738678234_macbook_v1_player_req.json # request metadata
āāā 1738678234_macbook_v1_player_res.json # response metadata
āāā 1738678234_macbook_v1_player_res_data.json # JSON body
āāā 1738678234_macbook_v1_player_res.html # HTML body (if HTML response)
āāā 1738678234_macbook_v1_player_err.json # error metadata
`json`
{
"url": "https://api.example.com/v1/player",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"data": {
"videoId": "dQw4w9WgXcQ"
}
}
`json`
{
"status": 200,
"statusText": "OK",
"headers": {
"content-type": "application/json",
"content-length": "46280"
},
"duration": 234
}
`json`
{
"message": "Request failed with status code 500",
"code": "ERR_BAD_RESPONSE",
"status": 500,
"statusText": "Internal Server Error",
"duration": 89,
"data": {
"error": "Something went wrong"
}
}
Attaches logging interceptors to an axios instance.
`typescript
import axios from 'axios';
import { attachLogger } from 'awesome-axios-logger';
const client = axios.create({ baseURL: 'https://api.example.com' });
const logger = attachLogger(client, {
dir: './logs',
filename: ({ ts, path, kind, ext }) => ${ts}_${path}_${kind}.${ext},
});
console.log(logger.logDir); // './logs'
`
Options:
| Option | Type | Required | Description |
|--------|------|----------|-------------|
| dir | string | Yes | Directory for log files |filename
| | FilenameFunction | No | Custom filename generator |
Creates interceptors without auto-attaching. Use this for manual interceptor setup.
`typescript
import { createLoggerInterceptors } from 'awesome-axios-logger';
const logger = createLoggerInterceptors({ dir: './logs' });
client.interceptors.request.use(logger.request);
client.interceptors.response.use(logger.response, logger.error);
`
Low-level utility to save a log file with auto-created directories.
`typescript
import { saveLog } from 'awesome-axios-logger';
await saveLog('./logs/custom.json', JSON.stringify({ hello: 'world' }, null, 2));
`
Control logging on a per-request basis:
| Option | Type | Description |
|--------|------|-------------|
| logAs | string | Override path for this request |skipLog
| | boolean | Skip logging entirely |
`typescript
// Skip logging
await client.get('/health', { skipLog: true });
// Custom name in logs
await client.get('/v1/get_user_info', { logAs: 'user' });
// ā 1738678234_macbook_user_req.json (instead of v1_get_user_info)
`
The filename function receives parameters about the request and returns the filename:
`typescript`
interface FilenameParams {
ts: number; // Unix timestamp (seconds)
hostname: string; // Machine hostname (sanitized)
url: string; // Full request URL
path: string; // Path from URL (sanitized: /v1/get_player ā v1_player)
kind: 'req' | 'res' | 'err';
ext: 'json' | 'html' | 'txt';
}
Examples:
`typescript${date}/${ts}_${path}_${kind}.${ext}
// Group by date
attachLogger(client, {
dir: './logs',
filename: ({ ts, path, kind, ext }) => {
const date = new Date(ts * 1000).toISOString().split('T')[0];
return ;
},
});
// ā ./logs/2026-02-04/1738678234_v1_player_req.json
// Group by videoId
const videoId = 'abc123';
attachLogger(client, {
dir: './logs',
filename: ({ ts, path, kind, ext }) => ${videoId}/${ts}_${path}_${kind}.${ext},
});
// ā ./logs/abc123/1738678234_v1_player_req.json
// Minimal format (without hostname)
attachLogger(client, {
dir: './logs',
filename: ({ ts, path, kind, ext }) => ${ts}_${path}_${kind}.${ext},`
});
// ā ./logs/1738678234_v1_player_req.json
awesome-axios-logger includes comprehensive TypeScript definitions:
`typescript`
import type {
LoggerOptions,
LoggerInterceptors,
FilenameParams,
FilenameFunction,
LogKind, // 'req' | 'res' | 'err'
LogExt, // 'json' | 'html' | 'txt'
} from 'awesome-axios-logger';
The library exports utility functions used internally:
`typescript`
import {
sanitize, // Sanitize string for filenames
getPathFromUrl, // Extract and sanitize path from URL
getHostname, // Get sanitized system hostname
detectExt, // Detect file extension from content
formatSize, // Format bytes to human readable (B, KB, MB)
getDataSize, // Get data size in bytes
defaultFilename,// Default filename function
buildFilepath, // Build full filepath from components
} from 'awesome-axios-logger';
- axios-logger ā request/response logging
- axios-debug-log ā debug-style logging
- axios-vcr ā record/replay requests
- axios-adapter-logger ā adapter-based logging
- @new10com/axios-logger ā structured logging
We welcome contributions! Please follow these steps:
1. Fork the repository
2. Create your feature branch (git checkout -b feature/amazing-feature)npm test
3. Make your changes and add tests
4. Ensure all tests pass ()git commit -m 'Add some amazing feature'
5. Commit your changes ()git push origin feature/amazing-feature`)
6. Push to the branch (
7. Open a Pull Request
- GitHub Repository
- NPM Package
- Issues & Bug Reports
MIT Ā© Igor Suvorov
---
awesome-axios-logger ā _Log every HTTP call_ š”
---