awesome-axios-logger
v1.0.0
Published
Axios interceptors for automatic HTTP request/response/error logging to console & files
Maintainers
Readme
📡 awesome-axios-logger
🚀 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.
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');Features
- 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) - Console output via
@lsk4/log(pino-style) - Zero config — just specify a directory
Installation
npm install axios awesome-axios-logger Import
import { attachLogger, createLoggerInterceptors } from 'awesome-axios-logger';Quick Start
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' });Console output
Uses @lsk4/log — a JSON-compatible logger (pino-style).
Enable logs via environment variable:
DEBUG=axios node app.jsExample output:
[axios] -> GET v1_player (124B)
[axios] <- v1_player 200 json (45.2KB) 234msOn error:
[axios] -> POST submit (1.2KB)
[axios] <- submit 500 json (156B) 89msLog file structure
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 metadataRequest log (*_req.json)
{
"url": "https://api.example.com/v1/player",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"data": {
"videoId": "dQw4w9WgXcQ"
}
}Response log (*_res.json)
{
"status": 200,
"statusText": "OK",
"headers": {
"content-type": "application/json",
"content-length": "46280"
},
"duration": 234
}Error log (*_err.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"
}
}API Reference
attachLogger(instance, options) → LoggerInterceptors
Attaches logging interceptors to an axios instance.
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 |
createLoggerInterceptors(options) → LoggerInterceptors
Creates interceptors without auto-attaching. Use this for manual interceptor setup.
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);saveLog(filepath, content)
Low-level utility to save a log file with auto-created directories.
import { saveLog } from 'awesome-axios-logger';
await saveLog('./logs/custom.json', JSON.stringify({ hello: 'world' }, null, 2));Per-request options
Control logging on a per-request basis:
| Option | Type | Description |
|--------|------|-------------|
| logAs | string | Override path for this request |
| skipLog | boolean | Skip logging entirely |
// 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)Custom filename
The filename function receives parameters about the request and returns the filename:
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:
// Group by date
attachLogger(client, {
dir: './logs',
filename: ({ ts, path, kind, ext }) => {
const date = new Date(ts * 1000).toISOString().split('T')[0];
return `${date}/${ts}_${path}_${kind}.${ext}`;
},
});
// → ./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.jsonType Definitions
awesome-axios-logger includes comprehensive TypeScript definitions:
import type {
LoggerOptions,
LoggerInterceptors,
FilenameParams,
FilenameFunction,
LogKind, // 'req' | 'res' | 'err'
LogExt, // 'json' | 'html' | 'txt'
} from 'awesome-axios-logger';Utility Functions
The library exports utility functions used internally:
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';Inspired by
- 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
Contributing
We welcome contributions! Please follow these steps:
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Make your changes and add tests
- Ensure all tests pass (
npm test) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Resources
License
MIT © Igor Suvorov
awesome-axios-logger — Log every HTTP call 📡
