npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

awesome-axios-logger

v1.0.0

Published

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

Readme

📡 awesome-axios-logger

LSK.js NPM version Tests TypeScript + ESM Install size Bundle size License Ask me in Telegram

🚀 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.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

Log 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 metadata

Request 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.json

Type 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

Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes and add tests
  4. Ensure all tests pass (npm test)
  5. Commit your changes (git commit -m 'Add some amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

Resources

License

MIT © Igor Suvorov


awesome-axios-loggerLog every HTTP call 📡