@geekmidas/logger

中文文档
9.6.1发布于 2026/11/16TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 1.6万

A simple and flexible logging library for Node.js and the browser

原始使用文档
文档目录25 节
  1. Features
  2. Installation
  3. Quick Start
  4. Pino Logger
  5. Sensitive Data Redaction
  6. Enable with Defaults
  7. Default Redacted Fields
  8. Add Custom Paths (Merged with Defaults)
  9. Override Defaults
  10. Custom Censor and Remove
  11. Path Syntax
  12. API Reference
  13. Logger Interface
  14. Log Levels
  15. ConsoleLogger
  16. Usage Examples
  17. Basic Logging
  18. Structured Logging
  19. Child Loggers
  20. Request Context Pattern
  21. Integration with Services
  22. Custom Logger Implementation
  23. TypeScript Support
  24. Best Practices
  25. License

@geekmidas/logger

A simple and flexible structured logging library for Node.js and browsers with child logger support and context inheritance.

Features

  • Standard Interface: Common logger interface with multiple log levels (debug, info, warn, error, fatal, trace)
  • Structured Logging: Support for both structured (object + message) and simple (message only) logging
  • Child Loggers: Create child loggers with inherited context
  • Multiple Implementations: ConsoleLogger for simple use, PinoLogger for production
  • Sensitive Data Redaction: Built-in redaction for passwords, tokens, API keys, and more
  • TypeScript: Full TypeScript support with type-safe logging

Installation

pnpm add @geekmidas/logger

Quick Start

import { ConsoleLogger } from '@geekmidas/logger';

// Create logger with initial context
const logger = new ConsoleLogger({ app: 'myApp', version: '1.0.0' });

// Structured logging
logger.info({ userId: 123, action: 'login' }, 'User logged in');
// Output: { app: 'myApp', version: '1.0.0', userId: 123, action: 'login', ts: 1234567890 } User logged in

// Simple logging
logger.info('Application started');
// Output: { app: 'myApp', version: '1.0.0', ts: 1234567890 } Application started

// Error logging
logger.error({ error, operation: 'fetchUser' }, 'Failed to fetch user');

Pino Logger

For production use, the package provides a Pino-based logger with high performance and built-in redaction support.

import { createLogger } from '@geekmidas/logger/pino';

const logger = createLogger({
  level: 'info',
  pretty: true,  // Pretty printing in development
  redact: true,  // Enable sensitive data redaction
});

logger.info({ userId: 123 }, 'User logged in');

Sensitive Data Redaction

The Pino logger includes built-in redaction to automatically mask sensitive data like passwords, tokens, and API keys.

Enable with Defaults

import { createLogger } from '@geekmidas/logger/pino';

const logger = createLogger({ redact: true });

// Sensitive data is automatically masked
logger.info({ password: 'secret123', user: 'john' }, 'Login attempt');
// Output: { password: '[Redacted]', user: 'john' } Login attempt

logger.info({ headers: { authorization: 'Bearer xyz' } }, 'Request');
// Output: { headers: { authorization: '[Redacted]' } } Request

Default Redacted Fields

When redact: true, the following fields are automatically masked:

  • Authentication: password, pass, passwd, secret, token, accessToken, refreshToken, apiKey, api_key, authorization, credentials
  • Headers: headers.authorization, headers.cookie, headers["x-api-key"]
  • Personal Data: ssn, creditCard, cardNumber, cvv, pin
  • Secrets: connectionString, databaseUrl
  • Wildcards: *.password, *.secret, *.token (catches nested fields)

Add Custom Paths (Merged with Defaults)

const logger = createLogger({
  redact: ['user.ssn', 'payment.cardNumber'],
});

// Both custom paths AND defaults are redacted
logger.info({ password: 'secret', user: { ssn: '123-45-6789' } }, 'Data');
// Output: { password: '[Redacted]', user: { ssn: '[Redacted]' } } Data

Override Defaults

Use resolution: 'override' to disable default paths and use only your custom paths:

const logger = createLogger({
  redact: {
    paths: ['myCustomSecret'],
    resolution: 'override',
  },
});

// Only 'myCustomSecret' is redacted, defaults are ignored
logger.info({ password: 'visible', myCustomSecret: 'hidden' }, 'Data');
// Output: { password: 'visible', myCustomSecret: '[Redacted]' } Data

Custom Censor and Remove

// Custom censor string
const logger = createLogger({
  redact: {
    paths: ['secret'],
    censor: '***HIDDEN***',
  },
});

// Remove fields entirely instead of masking
const logger2 = createLogger({
  redact: {
    paths: ['temporaryData'],
    remove: true,
  },
});

Path Syntax

Redaction paths support dot notation and wildcards:

redact: [
  'password',           // Top-level field
  'user.password',      // Nested field
  'users[*].password',  // Array wildcard
  '*.secret',           // Any object's 'secret' field
  'headers["x-api-key"]', // Bracket notation for special chars
]

API Reference

Logger Interface

interface Logger {
  debug: LogFn;
  info: LogFn;
  warn: LogFn;
  error: LogFn;
  fatal: LogFn;
  trace: LogFn;
  child: (obj: object) => Logger;
}

Log Levels

  • trace - Most detailed information
  • debug - Verbose information for debugging
  • info - General informational messages
  • warn - Potentially harmful situations
  • error - Error events that might still allow the application to continue
  • fatal - Severe errors that will likely cause the application to abort

ConsoleLogger

class ConsoleLogger implements Logger {
  constructor(data?: object)

  debug: LogFn
  info: LogFn
  warn: LogFn
  error: LogFn
  fatal: LogFn
  trace: LogFn
  child(obj: object): Logger
}

Usage Examples

Basic Logging

import { ConsoleLogger } from '@geekmidas/logger';

const logger = new ConsoleLogger({ service: 'api', environment: 'production' });

// Different log levels
logger.trace('Entering function');
logger.debug({ query: 'SELECT * FROM users' }, 'Executing query');
logger.info({ requestId: 'abc123' }, 'Request received');
logger.warn({ memoryUsage: '90%' }, 'High memory usage detected');
logger.error({ error: new Error('Connection failed') }, 'Database error');
logger.fatal({ exitCode: 1 }, 'Critical system failure');

Structured Logging

const logger = new ConsoleLogger({ app: 'myApp' });

// Log with context object
logger.info(
  {
    userId: 123,
    action: 'purchase',
    productId: 'prod_456',
    amount: 29.99
  },
  'Purchase completed'
);

// Multiple additional arguments
logger.info(
  { traceId: 'trace_123' },
  'Request processed in %dms',
  150
);

Child Loggers

Child loggers inherit all context from their parent and add their own:

const parentLogger = new ConsoleLogger({
  app: 'myApp',
  environment: 'production'
});

// Create child logger for authentication module
const authLogger = parentLogger.child({ module: 'auth' });
authLogger.info({ userId: 123 }, 'User authenticated');
// Output: { app: 'myApp', environment: 'production', module: 'auth', userId: 123, ts: ... }

// Create child logger for database module
const dbLogger = parentLogger.child({ module: 'database' });
dbLogger.debug({ query: 'SELECT ...' }, 'Query executed');
// Output: { app: 'myApp', environment: 'production', module: 'database', query: 'SELECT ...', ts: ... }

// Child loggers can be nested
const userDbLogger = dbLogger.child({ table: 'users' });
userDbLogger.info({ rowsAffected: 1 }, 'Record inserted');
// Output: { app: 'myApp', environment: 'production', module: 'database', table: 'users', rowsAffected: 1, ts: ... }

Request Context Pattern

import type { Logger } from '@geekmidas/logger';

function handleRequest(logger: Logger, requestId: string) {
  // Create request-scoped logger
  const requestLogger = logger.child({ requestId });

  requestLogger.info('Processing request');

  try {
    processPayment(requestLogger);
    requestLogger.info('Request completed');
  } catch (error) {
    requestLogger.error({ error }, 'Request failed');
  }
}

function processPayment(logger: Logger) {
  const paymentLogger = logger.child({ operation: 'payment' });
  paymentLogger.debug({ amount: 100 }, 'Processing payment');
  // All context is preserved: { requestId, operation, amount, ts }
}

Integration with Services

class UserService {
  private logger: Logger;

  constructor(logger: Logger) {
    this.logger = logger.child({ service: 'UserService' });
  }

  async createUser(data: UserData) {
    this.logger.info({ email: data.email }, 'Creating user');

    try {
      const user = await this.db.insert(data);
      this.logger.info({ userId: user.id }, 'User created successfully');
      return user;
    } catch (error) {
      this.logger.error({ error, email: data.email }, 'Failed to create user');
      throw error;
    }
  }

  async deleteUser(userId: string) {
    const logger = this.logger.child({ userId, operation: 'delete' });

    logger.info('Deleting user');
    await this.db.delete(userId);
    logger.info('User deleted');
  }
}

Custom Logger Implementation

You can implement the Logger interface for custom logging backends:

import type { Logger, LogFn } from '@geekmidas/logger';

class CustomLogger implements Logger {
  constructor(private context: object = {}) {}

  private createLogFn(level: string): LogFn {
    return (obj: any, msg?: string, ...args: any[]) => {
      // Your custom logging implementation
      const logEntry = {
        level,
        ...this.context,
        ...obj,
        timestamp: new Date().toISOString(),
        message: msg
      };

      // Send to your logging service
      yourLoggingService.send(logEntry);
    };
  }

  debug: LogFn = this.createLogFn('debug');
  info: LogFn = this.createLogFn('info');
  warn: LogFn = this.createLogFn('warn');
  error: LogFn = this.createLogFn('error');
  fatal: LogFn = this.createLogFn('fatal');
  trace: LogFn = this.createLogFn('trace');

  child(obj: object): Logger {
    return new CustomLogger({ ...this.context, ...obj });
  }
}

TypeScript Support

The library is written in TypeScript and provides full type definitions:

import type { Logger, LogFn } from '@geekmidas/logger';

// Use Logger type for dependency injection
function createService(logger: Logger) {
  return {
    doWork() {
      logger.info('Working...');
    }
  };
}

// LogFn type for custom implementations
const customLog: LogFn = (obj, msg) => {
  console.log(obj, msg);
};

Best Practices

  1. Create Base Logger Early: Initialize your base logger at application startup with static context

    const baseLogger = new ConsoleLogger({
      app: 'myApp',
      version: process.env.APP_VERSION,
      environment: process.env.NODE_ENV
    });
    
  2. Use Child Loggers: Create child loggers for different modules/contexts rather than passing context repeatedly

    const authLogger = baseLogger.child({ module: 'auth' });
    const dbLogger = baseLogger.child({ module: 'db' });
    
  3. Structured Over String: Prefer structured logging with context objects over string concatenation

    // Good
    logger.info({ userId, action: 'login', ip }, 'User logged in');
    
    // Avoid
    logger.info(`User ${userId} logged in from ${ip}`);
    
  4. Include Context: Add relevant context to make logs searchable and debuggable

    logger.error({
      error: err,
      userId,
      requestId,
      operation: 'fetchUser'
    }, 'Operation failed');
    
  5. Dependency Injection: Pass logger as dependency rather than importing globally

    class MyService {
      constructor(private logger: Logger) {}
    }
    

License

MIT

版本与发布记录

@geekmidas/logger 共发布 203 个版本,首次发布于 2025/10/20;过去 12 个月发布了 202 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
9.6.1latest2026/11/16今天
10.0.0-alpha.185alpha2026/11/16今天
10.0.0-alpha.1842026/11/16今天
10.0.0-alpha.1832026/11/16今天
10.0.0-alpha.1822026/11/132 天前
10.0.0-alpha.1812026/11/133 天前

关于 @geekmidas/logger 的常见问题

@geekmidas/logger 是什么?

A simple and flexible logging library for Node.js and the browser

如何安装 @geekmidas/logger?

在项目目录运行 npm install @geekmidas/logger,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:pino(~10.0.0)、pino-pretty(~13.1.2)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@geekmidas/logger 支持 TypeScript 吗?

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

@geekmidas/logger 支持 ESM 还是 CommonJS?

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

@geekmidas/logger 可以商用吗?

@geekmidas/logger 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@geekmidas/logger 的下载量有多少?

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

@geekmidas/logger 还在维护吗?

最新版本 9.6.1 发布于 2026/11/16(今天);至今共发布 203 个版本,其中过去 12 个月发布了 202 个;首次发布于 2025/10/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。