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 🙏

© 2025 – Pkg Stats / Ryan Hefner

firstlog

v0.0.4

Published

Modern middleware based logger for Express.js

Downloads

10

Readme

Features

  • 🚀 Easy Integration - Simple Express middleware setup
  • 📊 Performance Monitoring - Track request duration and identify slow requests
  • 🌍 Geographic Tracking - Optional GeoIP location tracking
  • 🔒 Security - Mask sensitive fields in logs
  • 📝 Flexible Logging - Outputs is JSON object format
  • 🎯 Selective Logging - Filter by paths, errors, or custom conditions
  • 📦 TypeScript Support - Full TypeScript definitions included
  • 🔧 Highly Configurable - Extensive customization options

Installation

npm install firstlog

To use the optional GeoIP feature, you must also install geoip-lite:

npm install geoip-lite

Quick Start

import express from "express";
import { logger } from "firstlog";

const app = express();

// Basic usage
app.use(
  logger({
    logFile: "./logs/access.log",
  })
);

// Your routes
app.get("/", (req, res) => {
  res.json({ message: "Hello World" });
});

app.listen(3000);

Configuration Options

Basic Options

| Option | Type | Default | Description | | ------------- | ---------- | ----------------------- | --------------------------------- | | logFile | string | Required | Path to the log file | | maskFields | string[] | ['password', 'token'] | Fields to mask in logs | | captureBody | boolean | true | Whether to capture request body | | prettyPrint | boolean | false | Format JSON logs with indentation |

Advanced Options

| Option | Type | Default | Description | | ----------------- | ---------- | ---------------- | -------------------------------------------------- | | onlyLogOnError | boolean | false | Only log requests that result in errors (4xx, 5xx) | | maxBodySize | number | 1024 | Maximum body size to log (in bytes) | | slowThresholdMs | number | 1000 | Threshold for marking requests as slow | | excludePaths | string[] | [] | Paths to exclude from logging | | requestIdHeader | string | 'x-request-id' | Header name for request ID |

Feature Toggles

| Option | Type | Default | Description | | ----------------- | --------- | ------- | ------------------------------------- | | trackQuery | boolean | false | Include query parameters in logs | | trackOrigin | boolean | false | Track the origin of the request | | enableGeoIP | boolean | false | Enable geographic IP tracking | | logHeaders | boolean | false | Include request headers in logs | | logParams | boolean | false | Include route parameters in logs | | logResponseBody | boolean | false | Include response body snippet in logs |

Callbacks

| Option | Type | Description | | ----------- | -------------------------- | ------------------------------------ | | trackUser | (req: Request) => string | Custom function to identify users | | onLog | (logEntry) => void | Callback executed for each log entry |

Usage Examples

Basic Logging

import { logger } from "firstlog";

app.use(
  logger({
    logFile: "./logs/app.log",
  })
);

Advanced Configuration

app.use(
  logger({
    logFile: "./logs/app.log",
    maskFields: ["password", "token", "apiKey"],
    captureBody: true,
    trackQuery: true,
    enableGeoIP: true, // Requires geoip-lite to be installed
    slowThresholdMs: 500,
    prettyPrint: true,
    excludePaths: ["/health", "/metrics"],
    trackUser: (req) => req.user?.id || "anonymous",
    onLog: (logEntry) => {
      if (logEntry.slow) {
        console.warn(`Slow request detected: ${logEntry.route}`);
      }
    },
  })
);

Error-Only Logging

app.use(
  logger({
    logFile: "./logs/errors.log",
    onlyLogOnError: true,
    logResponseBody: true,
  })
);

External Service Integration

app.use(
  logger({
    logFile: "./logs/app.log",
    onLog: (logEntry) => {
      // Send to your monitoring service
      analytics.track("request", logEntry);
    },
  })
);

Log Format

Each log entry contains the following information:

{
  "requestId": "550e8400-e29b-41d4-a716-446655440000",
  "timestamp": "2024-01-15T10:30:45.123Z",
  "method": "POST",
  "route": "/api/users",
  "status": 201,
  "ip": "192.168.1.100",
  "durationMs": 234.56,
  "slow": false,
  "user": "user123",
  "body": { "name": "John Doe", "password": "****" },
  "query": { "page": "1" },
  "headers": { "user-agent": "Mozilla/5.0...", "authorization": "****" },
  "params": { "id": "123" },
  "responseSnippet": "{\"success\": true, \"id\": \"456\"}",
  "location": {
    "country": "US",
    "region": "CA",
    "city": "San Francisco"
  }
}

TypeScript Support

Firstlog is built with TypeScript and includes comprehensive type definitions:

import { LoggerOptions, logger } from "firstlog";

const options: LoggerOptions = {
  logFile: "./logs/app.log",
  maskFields: ["password"],
  captureBody: true,
};

app.use(logger(options));

Performance Considerations

  • Body Capture: Disable captureBody for high-throughput applications
  • GeoIP: GeoIP lookups add latency and require the geoip-lite peer dependency. Use only when necessary.
  • Memory Usage: Set appropriate maxBodySize to prevent memory issues

Security

  • Sensitive fields are automatically masked using the maskFields option
  • Request IDs are generated using nanoid package

License

This project is licensed under the Usage-Only License.

Dependencies

  • express: Web framework compatibility
  • nanoid: Secure request ID generation

Peer Dependencies

  • geoip-lite (optional): For geographic IP tracking.

Authors

Conclusion

If you like this package, show your support & love!

buy me a coffee

Changelog

v0.0.1

  • Initial release
  • Basic logging functionality
  • TypeScript support
  • GeoIP integration
  • Performance monitoring
  • Security features

v0.0.2

  • Minor Fixes
  • Updated Readme

v0.0.3

  • Reduced package size under 100KB
  • Replaced uuid with nanoid
  • Modularized geoip-lite as an optional peer dependency to reduce bundle size for users who do not need the GeoIP feature.

v0.0.4

  • Fixed an issue where geoip-lite was getting installed automatically

Made with ❤️ by Aditya