glog-nodejs
v2.0.0
Published
Node.js logging library compatible with glog format
Maintainers
Readme
glog-nodejs - Node.js Logging Library
一个兼容 Go glog 格式的 Node.js 日志库,使用 TypeScript 编写。
特性
- 🎯 与 Go glog 兼容的日志格式
- 📊 多种日志级别:DEBUG, INFO, WARN, ERROR, FATAL, PANIC
- 🏷️ 结构化日志字段支持
- 🔍 上下文日志追踪(trace_id, user_id 等)
- 📝 支持 Console 和 JSON 格式输出
- 🔧 灵活的配置选项
- 🧵 异步上下文隔离(AsyncLocalStorage)
- 📦 TypeScript 支持
安装
npm install glog-nodejs
# or
yarn add glog-nodejs快速开始
基础使用
import * as glog from 'glog-nodejs';
// 简单日志
glog.info('Application started');
glog.warn('High memory usage');
glog.error('Connection failed');
// 格式化日志
glog.infof('User %s logged in', 'Alice');
glog.debugf('Processing %d items', 42);带字段的日志
import * as glog from 'glog-nodejs';
// 添加 trace_id 字段(显示在方括号中)
const logger = glog.defaultLogger().named('Runner');
const traceId = '59d428f7843866bd2863561f23c0c657';
const log = logger.withField(traceId, '');
log.info('🚀 Initializing Ollama model: gemma3:27b');
// 输出: [2025-11-15 17:10:29.461] [info] [Runner] main.ts:10 [59d428f7843866bd2863561f23c0c657] 🚀 Initializing Ollama model: gemma3:27b
// 添加多个字段
const pluginName = 'Plugin langchain_ollama_python';
const log2 = logger.withField(traceId, '').withField(pluginName, '');
log2.info('📤 Sending prompt to model...');错误日志
import * as glog from 'glog-nodejs';
try {
throw new Error('Something went wrong');
} catch (e) {
glog.withError(e as Error).error('Operation failed');
}上下文日志(请求追踪)
import * as glog from 'glog-nodejs';
// 初始化上下文
const logger = glog.defaultLogger().named('API');
glog.toContext(logger);
// 添加追踪 ID
glog.addTraceId('a1b2c3d4e5f6g7h8');
// 所有字段自动包含在日志中
let log = glog.extractEntry();
log.info('Request started');
// 添加更多字段
glog.addField('user_id', '123');
glog.addField('method', 'POST');
log = glog.extractEntry();
log.info('Request completed');自定义配置
import * as glog from 'glog-nodejs';
import { Level, Options } from 'glog-nodejs';
// 创建配置
const options = new Options({ level: Level.DEBUG });
options.withStdoutOutputPath();
options.withOutputPath('logs/app.log');
// 应用配置
glog.setDefaultLoggerConfig(options);
glog.debug('Debug logging enabled');JSON 格式输出
import * as glog from 'glog-nodejs';
import { Options } from 'glog-nodejs';
const options = new Options();
options.withJsonEncoding().withStdoutOutputPath();
glog.setDefaultLoggerConfig(options);
glog.info('This is JSON formatted');
// 输出: {"ts":"2024-01-01 12:00:00.000","level":"info","caller":"example.ts:10","msg":"This is JSON formatted"}日志级别
import { Level } from 'glog-nodejs';
Level.DEBUG // -1: 详细调试信息
Level.INFO // 0: 一般信息(默认)
Level.WARN // 1: 警告信息
Level.ERROR // 2: 错误信息
Level.DPANIC // 3: 开发环境 panic
Level.PANIC // 4: Panic 并抛出异常
Level.FATAL // 5: Fatal 并退出程序API 参考
包级函数
// 基础日志
glog.debug(msg: string): void
glog.info(msg: string): void
glog.warn(msg: string): void
glog.error(msg: string): void
// 格式化日志
glog.debugf(format: string, ...args: any[]): void
glog.infof(format: string, ...args: any[]): void
glog.warnf(format: string, ...args: any[]): void
glog.errorf(format: string, ...args: any[]): void
// 创建带字段的日志器
glog.withField(key: string, value: any): Logger
glog.withError(err: Error): Logger
// 配置
glog.setDefaultLoggerConfig(options: Options): void
glog.defaultLogger(): LoggerLogger 方法
const logger = glog.defaultLogger();
// 添加字段
logger.withField(key: string, value: any): Logger
logger.withFields(fields: Record<string, any>): Logger
logger.withError(err: Error): Logger
// 命名
logger.named(name: string): Logger
// 日志方法
logger.debug(...args: any[]): void
logger.info(...args: any[]): void
logger.warn(...args: any[]): void
logger.error(...args: any[]): void
logger.fatal(...args: any[]): void // 退出程序
logger.panic(...args: any[]): void // 抛出异常
// 格式化方法
logger.debugf(format: string, ...args: any[]): void
logger.infof(format: string, ...args: any[]): void
logger.warnf(format: string, ...args: any[]): void
logger.errorf(format: string, ...args: any[]): void
logger.fatalf(format: string, ...args: any[]): void
logger.panicf(format: string, ...args: any[]): void上下文日志
// 初始化上下文
glog.toContext(logger: Logger): ContextLogger
// 添加字段
glog.addField(key: string, value: any): void
glog.addFields(fields: Record<string, any>): void
glog.addTopField(key: string, value: any): void
// 特殊字段
glog.addTraceId(traceId: string): void
glog.addUserId(userId: number): void
glog.addPathname(pathname: string): void
// 提取
glog.extractEntry(): Logger
glog.extractTraceId(): string
glog.extractUserId(): number
glog.extractPathname(): string示例
查看 examples/ 目录获取更多示例:
basic_example.ts- 基础使用示例context_example.ts- 上下文日志示例simple_usage.ts- 简单使用示例
运行示例:
npm install
npm run example与 Python glog 的对应关系
| Python glog | glog-nodejs |
|-------------|-------------|
| glog.info() | glog.info() |
| glog.infof() | glog.infof() |
| glog.with_field() | glog.withField() |
| glog.with_error() | glog.withError() |
| glog.to_context() | glog.toContext() |
| glog.extract_entry() | glog.extractEntry() |
| glog.add_trace_id() | glog.addTraceId() |
开发
# 安装依赖
npm install
# 编译
npm run build
# 运行示例
npm run example许可证
MIT License
