@guiiai/logg

中文文档
1.2.12发布于 2026/09/29MITTypeScriptESM + CJS构建来源已验证近 30 天下载 4.3万

Yet another simple, nearly zero dependency, structural log compliance logger implementation.

原始使用文档
文档目录28 节
  1. Features
  2. Preview
  3. Installation
  4. Agent Skills
  5. Quick Start
  6. Usage Examples
  7. Basic Usage
  8. Adding Custom Fields
  9. Error Handling
  10. Child Loggers
  11. Auto-Context Logger
  12. Custom Time Format
  13. Error Processing
  14. API Reference
  15. Logger Factory Functions
  16. Logger Instance Methods
  17. Global Configuration
  18. Enums and Types
  19. Configuration
  20. Log Levels
  21. Output Formats
  22. Environment Support
  23. Node.js
  24. Browser
  25. Why @guiiai/logg?
  26. Star History
  27. Contributors
  28. Made with ❤

@guiiai/logg

npm version License: MIT

Yet another simple, nearly zero dependency, structural log compliance logger implementation.

Features

  • 🛠️ Stack Parse: Automatically captures and includes stack trace information for enhanced debugging
  • 📞 Caller Records: Provides detailed information about the calling function and file with clickable hyperlinks
  • 🗄️ JSON Format & stdout: Outputs logs in JSON format to stdout for easy parsing and integration with log management tools
  • 🎨 Pretty Format: Beautiful colored output for development with browser console support
  • 🔄 Drop-in Replacement: Can be used as a direct replacement for popular loggers like Winston
  • 📏 Best Practices: Implements industry best practices for structured logging
  • 🧩 Intuitive API: Simple and easy-to-use fluent API for quick integration
  • 🌐 Universal: Works in both Node.js and browser environments
  • ⚡ Zero Config: Works out of the box with sensible defaults

Preview

image

Installation

npm install @guiiai/logg

Agent Skills

Install the logg skill to your AI coding agent:

npx skills add guiiai/logg

Quick Start

import { initLogger, useGlobalLogger } from '@guiiai/logg'

// Initialize with defaults (Verbose level, Pretty format)
initLogger()

// Create a logger and start logging
const log = useGlobalLogger('MyApp')
log.log('Hello world!')

Usage Examples

Basic Usage

import { createLogg, Format, LogLevel, setGlobalFormat, setGlobalLogLevel } from '@guiiai/logg'

setGlobalLogLevel(LogLevel.Debug)
setGlobalFormat(Format.Pretty) // Otherwise it will output JSON

// Create a logger instance with a specific context
const log = createLogg('http/request').useGlobalConfig()

// Log messages with different levels
log.debug('Debugging info')
log.log('Regular log')
log.warn('Warning message')
log.error('Error occurred')

Adding Custom Fields

// Add single field
log
  .withField('requestId', req.id)
  .withField('url', req.url)
  .error('Resource not found (404)')

// Add multiple fields at once
log
  .withFields({
    userId: '12345',
    ip: '192.168.1.1',
    userAgent: 'Mozilla/5.0'
  })
  .log('User logged in')

Error Handling

try {
  // Some operation
}
catch (err) {
  // Automatically extracts error message, stack trace, and cause
  log.withError(err).error('Operation failed')

  // Or use errorWithError for more control
  log.errorWithError('Failed to process request', err)
}

Child Loggers

const parentLog = createLogg('app').useGlobalConfig()

// Create child logger with persistent fields
const childLog = parentLog.child({
  module: 'database',
  version: '1.0.0'
})

// All logs from childLog will include the parent fields
childLog.log('Connected to database')

Auto-Context Logger

import { createLogger } from '@guiiai/logg'

// Automatically includes file path and line number with clickable hyperlinks
const log = createLogger().useGlobalConfig()
log.log('This log knows where it came from!')

Custom Time Format

const log = createLogg('app')
  .useGlobalConfig()
  .withTimeFormatter((date) => {
    return date.toLocaleString('en-US', {
      timeZone: 'America/New_York'
    })
  })

log.log('Log with custom timestamp')

Error Processing

// Transform errors before logging
const log = createLogg('app')
  .useGlobalConfig()
  .withErrorProcessor((err) => {
    if (err instanceof CustomError) {
      // Add custom properties or transform the error
      return { ...err, customField: 'value' }
    }
    return err
  })

log.withError(someError).error('Processed error')

API Reference

Logger Factory Functions

createLogg(context: string): Logg

Creates a new logger instance with the specified context.

const log = createLogg('MyModule')

createLogger(context?: string): Logg

Creates a logger with automatic context from the call site (file path and line number). Includes clickable hyperlinks in supported terminals.

const log = createLogger() // Context is auto-generated
const log2 = createLogger('CustomContext') // Override with custom context

createGlobalLogger(context?: string): Logg

Creates a logger with automatic context and applies global configuration.

const log = createGlobalLogger()

initLogger(level?: LogLevel, format?: Format): void

Initializes global logger configuration with defaults.

import { Format, initLogger, LogLevel } from '@guiiai/logg'

initLogger(LogLevel.Verbose, Format.Pretty)

Aliases:

  • useLogg → createLogg
  • useLogger → createLogger
  • useGlobalLogger → createGlobalLogger

Logger Instance Methods

Configuration Methods

  • useGlobalConfig(): Logg - Applies global configuration to the logger instance
  • child(fields?: Record<string, any>): Logg - Creates a child logger with additional persistent fields
  • withContext(context: string): Logg - Sets context dynamically (returns cloned instance)
  • withLogLevel(logLevel: LogLevel): Logg - Sets log level dynamically (returns cloned instance)
  • withLogLevelString(logLevelString: LogLevelString): Logg - Sets log level using string (returns cloned instance)
  • withFormat(format: Format): Logg - Sets output format dynamically (returns cloned instance)
  • withFields(fields: Record<string, any>): Logg - Alias for child()
  • withField(key: string, value: any): Logg - Adds a single custom field
  • withError(err: Error | unknown): Logg - Attaches error object with automatic extraction of message, stack, and cause
  • withCallStack(errorLike: { message: string, stack?: string }): Logg - Adds call stack information
  • withTimeFormatter(fn: (date: Date) => string): Logg - Sets custom time formatter function
  • withErrorProcessor(fn: (err: Error | unknown) => Error | unknown): Logg - Sets custom error processor function

Logging Methods

  • debug(message: any, ...optionalParams: any[]): void - Logs debug-level message
  • verbose(message: any, ...optionalParams: any[]): void - Logs verbose-level message
  • log(message: any, ...optionalParams: any[]): void - Logs info-level message
  • warn(message: any, ...optionalParams: any[]): void - Logs warning-level message
  • error(message: any, stack?: string, ...optionalParams: any[]): void - Logs error-level message
  • errorWithError(message: any, err: Error | unknown, ...optionalParams: any[]): void - Logs error with automatic error extraction

Global Configuration

Log Level

import { getGlobalLogLevel, getGlobalLogLevelString, LogLevel, setGlobalLogLevel, setGlobalLogLevelString } from '@guiiai/logg'

setGlobalLogLevel(LogLevel.Debug)
const level = getGlobalLogLevel()

// Or use string-based methods
setGlobalLogLevelString('debug')
const levelString = getGlobalLogLevelString()

Format

import { Format, getGlobalFormat, setGlobalFormat } from '@guiiai/logg'

setGlobalFormat(Format.Pretty)
const format = getGlobalFormat()

Time Formatter

import { getGlobalTimeFormatter, setGlobalTimeFormatter } from '@guiiai/logg'

setGlobalTimeFormatter(date => date.toISOString())
const formatter = getGlobalTimeFormatter()

Enums and Types

LogLevel

enum LogLevel {
  Error = 0,
  Warning = 1,
  Log = 2,
  Verbose = 3,
  Debug = 4
}

LogLevelString

type LogLevelString = 'error' | 'warn' | 'log' | 'verbose' | 'debug'

Format

enum Format {
  JSON = 'json',
  Pretty = 'pretty'
}

Configuration

Log Levels

Log levels control which messages are output. Higher levels include all lower levels.

LevelValueDescription
Error0Only error messages
Warning1Errors and warnings
Log2Errors, warnings, and general logs
Verbose3All above plus verbose information
Debug4All messages including debug info

Output Formats

JSON Format

Structured JSON output, ideal for production environments and log aggregation tools.

{ "level": "log", "context": "app", "timestamp": "2024-01-01T00:00:00.000Z", "message": "User logged in", "fields": { "userId": "123" } }

Pretty Format

Human-readable colored output for development. Automatically detects browser environments and adjusts output accordingly.

[2024-01-01 00:00:00] LOG app: User logged in { userId: '123' }

Environment Support

Node.js

Full support for all features including:

  • Terminal hyperlinks (VS Code, iTerm2, etc.)
  • Colored output
  • Stack trace parsing

Browser

Optimized browser support with:

  • Console-friendly output
  • Proper object expansion in browser devtools
  • Automatic format detection

Why @guiiai/logg?

  • Lightweight: Minimal dependencies (only 3 runtime deps)
  • Type-safe: Full TypeScript support with complete type definitions
  • Flexible: Works in any environment without configuration
  • Developer-friendly: Beautiful output and clickable source links
  • Production-ready: JSON output for log aggregation systems

Star History

Star History Chart

Contributors

contributors

Made with ❤

版本与发布记录

@guiiai/logg 共发布 27 个版本,首次发布于 2024/08/01;过去 12 个月发布了 7 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.2.12latest2026/09/291 个月前
1.2.112025/12/1611 个月前
1.2.102025/12/1511 个月前
1.2.92025/12/1411 个月前
1.2.82025/12/1411 个月前
1.2.72025/12/1411 个月前

关于 @guiiai/logg 的常见问题

@guiiai/logg 是什么?

Yet another simple, nearly zero dependency, structural log compliance logger implementation.

如何安装 @guiiai/logg?

在项目目录运行 npm install @guiiai/logg,或使用 pnpm add / yarn add / bun add。

@guiiai/logg 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@guiiai/logg 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@guiiai/logg 可以商用吗?

@guiiai/logg 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@guiiai/logg 的下载量有多少?

根据 npm 官方下载统计,@guiiai/logg 在 2026/10/17 – 2026/11/15 这 30 天内被下载 43,094 次,日均约 1,436 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@guiiai/logg 还在维护吗?

最新版本 1.2.12 发布于 2026/09/29(1 个月前);至今共发布 27 个版本,其中过去 12 个月发布了 7 个;首次发布于 2024/08/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。