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

@via-cli/log-tools

v0.0.2

Published

A modern ESM logging library with customizable levels, colors, and prefixes

Readme

@via-cli/log-tools

npm version License: MIT

🚀 现代化 ESM 日志记录库 - 提供可自定义的日志级别、颜色和前缀,支持多环境适配器

✨ 功能特性

  • 🎨 多环境适配 - 自动检测并适配 Node.js 和浏览器环境
  • 🌈 颜色支持 - 基于 chalk 的丰富颜色和样式系统
  • 📊 多级别日志 - 内置 7 种日志级别,支持自定义级别
  • 高性能 - ESM 原生支持,零配置启动
  • 🔧 灵活配置 - 支持动态配置日志级别、前缀和适配器
  • 🎯 TypeScript - 完整的 TypeScript 类型支持
  • 📦 轻量级 - 最小化依赖,体积小
  • 🧪 测试友好 - 内置静默适配器,方便测试
  • 纯净模式 - 不经过任何格式化的原始输出,优先级最高

📦 安装

# npm
npm install @via-cli/log-tools

# pnpm
pnpm add @via-cli/log-tools

# yarn
yarn add @via-cli/log-tools

🏗️ 项目结构

packages/log-tools/
├── src/
│   ├── index.ts          # 主入口文件和 LogTools 命名空间
│   ├── Logger.ts         # Logger 类核心实现
│   ├── types/
│   │   └── index.ts      # TypeScript 类型定义
│   ├── adapters/
│   │   └── index.ts      # 多环境适配器实现
│   └── __tests__/        # 测试文件
├── examples/             # 使用示例
├── dist/                # 构建输出目录
├── package.json         # 包配置文件
├── tsconfig.json        # TypeScript 配置
├── tsup.config.js       # 构建配置
└── vitest.config.ts     # 测试配置

🚀 快速开始

基础使用

import LogTools from '@via-cli/log-tools';

// 基础日志记录
LogTools.info('app', 'Application started');
LogTools.warn('config', 'Using default configuration');
LogTools.error('db', 'Connection failed');
LogTools.success('task', 'Task completed successfully');

// 带参数的日志
LogTools.debug('user', 'User data:', { id: 123, name: 'John' });

配置和自定义

import { LogTools } from '@via-cli/log-tools';

// 配置日志器
LogTools.configure({
  level: 'debug',           // 设置日志级别
  heading: 'MyApp',         // 设置应用前缀
  enableColors: true        // 启用颜色
});

// 查看当前配置
console.log(LogTools.getConfig());

📊 日志级别

内置日志级别(按优先级从低到高):

| 级别 | 数值 | 描述 | 颜色 | |------|------|------|------| | silly | -Infinity | 最详细的调试信息 | 默认 | | verbose | 1000 | 详细信息 | 默认 | | debug | 1000 | 调试信息(verbose 别名) | 默认 | | info | 2000 | 普通信息 | 默认 | | warn | 4000 | 警告信息 | 🟡 黄色 | | error | 5000 | 错误信息 | 🔴 红色加粗 | | success | 2000 | 成功信息 | 🟢 绿色加粗 |

设置日志级别

// 只显示 info 级别及以上的日志
LogTools.setLevel('info');

// 显示所有级别的日志
LogTools.setLevel('silly');

🔧 API 参考

LogTools 命名空间方法

配置方法

  • configure(options: LogOptions): Logger - 配置日志器
  • getConfig(): object - 获取当前配置

日志记录方法

  • silly(prefix: string, message: string, ...args: any[]): void
  • verbose(prefix: string, message: string, ...args: any[]): void
  • debug(prefix: string, message: string, ...args: any[]): void
  • info(prefix: string, message: string, ...args: any[]): void
  • warn(prefix: string, message: string, ...args: any[]): void
  • error(prefix: string, message: string, ...args: any[]): void
  • success(prefix: string, message: string, ...args: any[]): void

高级功能方法

  • addLevel(name: string, level: number, style?: LogLevel['style']): void - 添加自定义日志级别
  • setLevel(level: string): void - 设置日志级别
  • getInstance(): Logger - 获取日志器实例

适配器方法

  • setAdapter(adapter: OutputAdapter): void - 设置输出适配器
  • getAdapter(): OutputAdapter - 获取当前适配器

分组和计时方法

  • group(label: string): void - 开始日志分组
  • groupEnd(): void - 结束日志分组
  • time(label: string): void - 开始计时
  • timeEnd(label: string): void - 结束计时并输出耗时

🎯 纯净模式方法

纯净模式提供不经过任何格式化处理的原始输出,优先级最高,不受日志级别限制。

  • pure(message: string, ...args: any[]): void - 纯净信息输出
  • pureWarn(message: string, ...args: any[]): void - 纯净警告输出
  • pureError(message: string, ...args: any[]): void - 纯净错误输出
// 普通模式(会被格式化)
LogTools.info('auth', '用户登录成功');
// 输出: [2025-10-24T06:00:01.876Z] INFO gogoal:auth 用户登录成功

// 纯净模式(保持原样)
LogTools.pure('用户登录成功');
// 输出: 用户登录成功

// 纯净模式不受日志级别限制
LogTools.setLevel('error');
LogTools.info('test', '这条不会显示');  // 不显示
LogTools.pure('这条会显示');            // 显示

配置选项 (LogOptions)

interface LogOptions {
  level?: string;              // 日志级别,默认 'info'
  heading?: string;            // 应用前缀,默认 'gogoal'
  enableColors?: boolean;      // 启用颜色,自动检测 TTY
  adapter?: OutputAdapter;     // 自定义输出适配器
  adapterOptions?: AdapterOptions; // 适配器配置
}

适配器配置 (AdapterOptions)

interface AdapterOptions {
  enableTimestamp?: boolean;   // 启用时间戳,默认 Node.js 环境为 true
  enableGroup?: boolean;       // 启用分组,默认浏览器环境为 true
  customPrefix?: string;       // 自定义前缀
}

🎨 多环境适配器

自动适配器(推荐)

import { LogTools } from '@via-cli/log-tools';

// 自动根据环境选择适配器
LogTools.info('app', 'This works in both Node.js and browser');

Node.js 适配器

import { LogTools, NodeAdapter } from '@via-cli/log-tools';

const nodeAdapter = new NodeAdapter({
  enableTimestamp: true,    // 显示时间戳
  enableGroup: false        // 禁用分组
});

LogTools.setAdapter(nodeAdapter);
LogTools.info('server', 'Server started on port 3000');
// 输出: [2023-10-21T10:30:45.123Z] INFO GOGOAL:SERVER Server started on port 3000

浏览器适配器

import { LogTools, BrowserAdapter } from '@via-cli/log-tools';

const browserAdapter = new BrowserAdapter({
  enableGroup: true,        // 启用分组(利用浏览器 DevTools)
  customPrefix: '[WEB]'     // 自定义前缀
});

LogTools.setAdapter(browserAdapter);
LogTools.group('User Operations');
LogTools.info('auth', 'User logged in');
LogTools.success('profile', 'Profile updated');
LogTools.groupEnd();

静默适配器(测试环境)

import { LogTools, SilentAdapter } from '@via-cli/log-tools';

// 测试环境下禁用所有日志输出
if (process.env.NODE_ENV === 'test') {
  LogTools.setAdapter(new SilentAdapter());
}

💡 使用示例

示例 1:基础应用日志

import LogTools from '@via-cli/log-tools';

// 配置应用
LogTools.configure({
  level: 'info',
  heading: 'MyApp',
  enableColors: true
});

// 应用启动
LogTools.info('init', 'Initializing application...');
LogTools.success('init', 'Application initialized successfully');

// 数据库连接
try {
  // 连接数据库的代码
  LogTools.success('db', 'Connected to database');
} catch (error) {
  LogTools.error('db', 'Failed to connect to database:', error.message);
}

// 用户操作
LogTools.info('auth', 'User attempting login');
LogTools.debug('auth', 'Login attempt details:', { username: 'john', timestamp: Date.now() });
LogTools.success('auth', 'User authenticated successfully');

示例 2:自定义日志级别

import { LogTools } from '@via-cli/log-tools';

// 添加审计日志级别
LogTools.addLevel('audit', 1500, {
  fg: 'cyan',
  bold: true
});

// 添加安全日志级别
LogTools.addLevel('security', 5500, {
  fg: 'magenta',
  bold: true,
  underline: true
});

// 使用自定义级别
LogTools.audit('system', 'User permissions changed');
LogTools.security('auth', 'Suspicious login attempt detected');

示例 3:Logger 类直接使用

import { Logger, NodeAdapter } from '@via-cli/log-tools';

// 创建专用日志器实例
const apiLogger = new Logger({
  heading: 'API',
  level: 'debug',
  adapter: new NodeAdapter({ enableTimestamp: true }),
  enableColors: true
});

const dbLogger = new Logger({
  heading: 'DB',
  level: 'warn',
  enableColors: false
});

// 分别使用不同的日志器
apiLogger.info('request', 'GET /api/users');
apiLogger.debug('response', 'Response time: 45ms');

dbLogger.warn('connection', 'Connection pool nearly exhausted');

示例 4:性能监控

import LogTools from '@via-cli/log-tools';

// 监控异步操作性能
async function processData(data) {
  LogTools.time('data-processing');
  LogTools.info('processor', `Processing ${data.length} records`);
  
  try {
    LogTools.group('Data Processing Steps');
    
    LogTools.time('validation');
    await validateData(data);
    LogTools.timeEnd('validation');
    LogTools.success('validation', 'Data validation completed');
    
    LogTools.time('transformation');
    const transformed = await transformData(data);
    LogTools.timeEnd('transformation');
    LogTools.success('transform', 'Data transformation completed');
    
    LogTools.time('saving');
    await saveData(transformed);
    LogTools.timeEnd('saving');
    LogTools.success('save', 'Data saved to database');
    
    LogTools.groupEnd();
    LogTools.timeEnd('data-processing');
    
    return transformed;
  } catch (error) {
    LogTools.error('processor', 'Processing failed:', error);
    throw error;
  }
}

示例 5:开发环境调试

import LogTools from '@via-cli/log-tools';

// 根据环境配置不同的日志级别
const isDevelopment = process.env.NODE_ENV === 'development';
const isProduction = process.env.NODE_ENV === 'production';

LogTools.configure({
  level: isDevelopment ? 'debug' : isProduction ? 'warn' : 'info',
  heading: 'MyApp',
  enableColors: !isProduction // 生产环境禁用颜色
});

// 开发调试信息
if (isDevelopment) {
  LogTools.debug('dev', 'Development mode enabled');
  LogTools.verbose('config', 'Current config:', process.env);
}

// 条件日志记录
function debugUser(user) {
  if (isDevelopment) {
    LogTools.group(`User Debug: ${user.id}`);
    LogTools.debug('user', 'Full user object:', user);
    LogTools.debug('permissions', 'User permissions:', user.permissions);
    LogTools.debug('session', 'Session data:', user.session);
    LogTools.groupEnd();
  }
}

示例 6:错误处理和日志记录

import LogTools from '@via-cli/log-tools';

class ApiService {
  async fetchUser(id) {
    LogTools.info('api', `Fetching user ${id}`);
    
    try {
      const response = await fetch(`/api/users/${id}`);
      
      if (!response.ok) {
        LogTools.warn('api', `API returned ${response.status} for user ${id}`);
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      
      const user = await response.json();
      LogTools.success('api', `Successfully fetched user ${id}`);
      LogTools.debug('api', 'User data:', user);
      
      return user;
    } catch (error) {
      LogTools.error('api', `Failed to fetch user ${id}:`, {
        error: error.message,
        stack: error.stack,
        timestamp: new Date().toISOString()
      });
      throw error;
    }
  }
}

🧪 测试支持

在测试环境中使用静默适配器:

// test-setup.js
import { LogTools, SilentAdapter } from '@via-cli/log-tools';

// 测试环境使用静默适配器
if (process.env.NODE_ENV === 'test') {
  LogTools.setAdapter(new SilentAdapter());
}

// 或者在特定测试中临时静默
describe('My Test Suite', () => {
  beforeEach(() => {
    LogTools.setAdapter(new SilentAdapter());
  });
  
  afterEach(() => {
    // 恢复默认适配器
    LogTools.setAdapter(LogTools.Adapters.createAdapter());
  });
});

🛠️ 开发流程

环境准备

# 1. 克隆项目
git clone <repository-url>
cd packages/log-tools

# 2. 安装依赖
pnpm install

# 3. 构建项目
pnpm build

开发命令

# 开发模式(监听文件变化)
pnpm dev

# 运行测试
pnpm test

# 监听模式测试
pnpm test:watch

# 测试覆盖率
pnpm test:coverage

# 测试 UI
pnpm test:ui

# 运行示例
pnpm test:examples

# 清理构建文件
pnpm clean

项目构建

项目使用 tsup 进行构建,配置文件 tsup.config.js

import { defineConfig } from 'tsup';

export default defineConfig({
  entry: ['src/index.ts'],
  format: ['esm'],        // 仅支持 ESM
  dts: true,             // 生成类型声明文件
  clean: true,           // 构建前清理
  splitting: false,      // 不进行代码分割
  sourcemap: true,       // 生成 source map
  shims: false,          // 不添加 polyfill
});

测试策略

使用 Vitest 进行单元测试:

  • 单元测试: 测试核心功能和边界情况
  • 适配器测试: 验证不同环境下的适配器行为
  • 集成测试: 测试完整的日志记录流程
  • 类型测试: 确保 TypeScript 类型正确性

🤝 贡献指南

  1. Fork 项目
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 创建 Pull Request

代码规范

  • 遵循 TypeScript 最佳实践
  • 保持 ESM 兼容性
  • 添加适当的类型注解
  • 编写单元测试
  • 更新相关文档

📄 许可证

本项目采用 MIT License 许可证。

🔗 相关链接


Made with ❤️ by @via-cli team