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

mm_logs

v1.6.5

Published

高性能 Node.js 日志模块,支持多级别日志、文件轮转、事件钩子和灵活配置。

Readme

mm_logs

高性能 Node.js 日志模块,支持多级别日志、文件轮转、事件钩子和灵活配置。

特性

  • 📝 多级别日志: debug, info, success, warn, error, fatal
  • 💾 文件轮转: 按大小自动分割日志文件
  • 🎨 双格式输出: 支持 JSON 和文本格式
  • 🖥️ 双路输出: 同时输出到控制台和文件
  • 🌐 HTTP 日志: 单独记录 HTTP 请求日志
  • 🔍 日志查询: 支持按日期、时间、关键词查询
  • 🎯 事件钩子: 支持日志记录前后的事件监听
  • 异步处理: 非阻塞日志写入,提高应用性能
  • 🧹 自动清理: 自动管理日志文件数量

安装

npm install mm_logs

快速开始

const { Log } = require('mm_logs');

// 创建日志实例
const logger = new Log({
    level: 'debug',
    dir: './logs',
    console: true,
    file: true
});

// 记录日志
logger.debug('调试信息');
logger.info('普通信息');
logger.success('成功信息');
logger.warn('警告信息');
logger.error('错误信息');
logger.fatal('致命错误');

// 记录带参数的日志
logger.info('用户登录', { username: 'admin', ip: '127.0.0.1' });

// 记录 HTTP 日志
logger.http('info', 'API 请求', { method: 'GET', url: '/api/users' });

配置选项

| 配置项 | 类型 | 默认值 | 描述 | |-------|------|-------|------| | level | string | 'debug' | 日志级别 | | dir | string | './log' | 日志文件目录 | | console | boolean | true | 是否输出到控制台 | | file | boolean | true | 是否输出到文件 | | max_size | number | 3145728 (3MB) | 单个日志文件最大大小(字节) | | max_files | number | 7 | 保留的日志文件最大数量 | | date_pattern | string | '_yyyy-MM-dd' | 日期格式 | | content_pattern | string | '%d{hh:mm:ss.SSS} [%p] - %m' | 日志内容格式 | | file_name_pattern | string | '{type}_{date}_{index}' | 文件名格式 | | is_json | boolean | false | 是否使用 JSON 格式输出 |

日志级别

日志级别从低到高排序:

  • debug: 调试信息,开发环境使用
  • info: 普通信息,记录程序运行状态
  • success: 成功信息,记录操作成功
  • warn: 警告信息,需要关注但不影响运行
  • error: 错误信息,功能异常但程序仍可运行
  • fatal: 致命错误,程序无法继续运行

高级用法

批量记录日志

logger.batch([
    { level: 'info', message: '用户登录', args: [{ username: 'admin' }] },
    { level: 'warn', message: '密码错误', args: [{ username: 'user123' }] }
]);

重新配置

// 动态更新配置
logger.reconfig({
    level: 'info',
    is_json: true,
    max_size: 5 * 1024 * 1024 // 5MB
});

日志查询

const result = logger.find({
    date: '2023-12-01',      // 查询日期
    start_time: '09:00:00',  // 起始时间
    end_time: '18:00:00',    // 结束时间
    keyword: 'error',        // 关键词
    page: 1,                 // 页码
    size: 50                 // 每页大小
});

console.log(result.logs);          // 日志列表
console.log(result.pagination);    // 分页信息

事件监听

// 日志记录前
logger.on('before_log', (data) => {
    // 可以在这里处理敏感信息脱敏
    console.log('准备记录日志:', data);
});

// 日志记录后
logger.on('record:after', (result) => {
    // 可以在这里进行性能监控
    console.log('日志记录完成:', result);
});

// 日志记录错误
logger.on('record:error', (error) => {
    console.error('日志记录出错:', error);
});

// 查询错误
logger.on('find:error', (error) => {
    console.error('日志查询出错:', error);
});

刷新与销毁

// 刷新日志缓存到磁盘
logger.flush().then(() => {
    console.log('日志已刷新');
});

// 销毁日志实例
logger.destroy().then(() => {
    console.log('日志实例已销毁');
});

日志文件

模块自动创建三种类型的日志文件:

  • debug_{date}_{index}.log: 记录 debug、info、success 级别
  • error_{date}_{index}.log: 记录 warn、error、fatal 级别
  • http_{date}_{index}.log: 记录 HTTP 相关日志

当文件大小超过 max_size 时,自动创建新文件(索引递增)。

最佳实践

1. 全局日志实例

// logger.js
const { Log } = require('mm_logs');

const logger = new Log({
    level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
    dir: './logs',
    console: true,
    file: true,
    is_json: process.env.NODE_ENV === 'production'
});

module.exports = logger;

2. Express 集成

const express = require('express');
const logger = require('./logger');
const app = express();

// HTTP 请求日志中间件
app.use((req, res, next) => {
    const startTime = Date.now();
    const originalSend = res.send;
    
    res.send = function(body) {
        const duration = Date.now() - startTime;
        const logData = {
            method: req.method,
            url: req.url,
            status: res.statusCode,
            duration: duration,
            ip: req.ip
        };
        
        // 根据状态码记录不同级别
        if (res.statusCode >= 500) {
            logger.http('error', 'HTTP 错误', logData);
        } else if (res.statusCode >= 400) {
            logger.http('warn', 'HTTP 警告', logData);
        } else {
            logger.http('info', 'HTTP 请求', logData);
        }
        
        return originalSend.call(this, body);
    };
    
    next();
});

app.get('/', (req, res) => {
    logger.debug('处理请求', { path: req.path });
    res.send('Hello World');
});

app.listen(3000);

3. 错误处理

// error-handler.js
const logger = require('./logger');

function handleError(err, req, res, next) {
    logger.error('应用错误', {
        message: err.message,
        stack: process.env.NODE_ENV === 'production' ? '' : err.stack,
        path: req.path,
        method: req.method
    });
    
    res.status(500).json({
        error: process.env.NODE_ENV === 'production' ? 'Internal Server Error' : err.message
    });
}

module.exports = handleError;

兼容性

支持 Node.js 12.x 及以上版本。

性能

  • 使用流式写入,避免阻塞主线程
  • 异步日志处理,提高应用响应速度
  • 自动轮转和清理,保持文件系统整洁
  • 优化的文件 I/O,减少磁盘操作开销

许可证

MIT License