@chax-at/log-sink

中文文档
2.0.2发布于 2025/08/29TypeScriptCommonJS近 30 天下载 3641

A Log Service

原始使用文档
文档目录8 节
  1. Usage
  2. Log Levels
  3. Tags, Attributes and Timestamps
  4. Drains
  5. ConsoleLogDrain
  6. GelfLogDrain
  7. FilesystemLogDrain
  8. OpenTelemetryLogDrain

LogSink

LogSink is a simple logging package that allows logs to be sent to multiple destinations. These destinations are called "drains".

Usage

The package provides a singleton instance of LogSink as a default export:

import LogSink from '@chax-at/log-sink';

Before use the LogSink instance must be configured with at least one drain:

LogSink.registerDrain(new ConsoleLogDrain(), {
    enabled: true,
    minLevel: LOGGING_CONSOLE_MINLEVEL,
    maxLevel: LOGGING_CONSOLE_MAXLEVEL,
});

The singleton instance can then be imported in any file and used for logging:

import LogSink from '@chax-at/log-sink';

LogSink.info('This is an info message');

Log Levels

LogSink only differentiates between four log levels. This is less than other logging solution, but is intended to make it clearer when to use each level. The numeric value of each level adheres to the syslog standard.

LevelNumericDescription
Error3An error occurred. Will trigger an alert. (depending on the drain)
Warn4A warning message. Will not trigger an alert but is visible on dashboards.
Info6An informational message, visible in production logs.
Debug7A debug message, typically filtered out in production environments.

In projects where exceptions are also used for non-serve errors, such as for token-expired exceptions, each exception should be associated with the appropriate error level. That is,

  • token expired would be a debug message
  • validation failed would be a warning message
  • PDF generation failed would be an error message
LogSink.error('This is an error message');
LogSink.warning('This is a warning message');
LogSink.info('This is an info message');
LogSink.debug('This is a debug message');           // Level 7

Tags, Attributes and Timestamps

In addition to a message, each of these methods takes an optional tag, attribute object and timestamp:

enum LogTags {
    Database = 'database',
}

LogSink.info('This is an info message', LogTags.Database, {attr1: 'value1', attr2: 'value2'}, new Date());

If the log level is not known at compile time, the log method can be used:

LogSink.log(LogLevel.Info, 'This is an info message');

If needed, you can create additional LogSink instances:

import {LogSink} from '@chax-at/log-sink';

const logSink = new LogSink();

Drains

The package provides two built-in drains: ConsoleLogDrain and GelfLogDrain. New drains can be added by implementing the ILogDrain interface.

Drains are registered using the registerDrain method. Using minLevel and maxLevel, the severity levels can be filtered on each drain. Additionally, logs can be filtered using the filter method and transformed using the transform method.

LogSink.registerDrain(new ConsoleLogDrain(), {
    enabled: true,
    minLevel: LOGGING_CONSOLE_MINLEVEL,
    maxLevel: LOGGING_CONSOLE_MAXLEVEL,
    filter: (options: LogOptions) => {
        return options.tag === LogTags.Database;
    },
    transform: (options: LogOptions) => {
        return {
            ...options,
            message: options.message.toUpperCase(),
        };
    },
});

ConsoleLogDrain

The ConsoleLogDrain logs messages to the console. It can be configured to log attributes and use color.

new ConsoleLogDrain({logAttributes: true, useColor: true});

GelfLogDrain

The GelfLogDrain logs messages to any GELF-capable server, such as Graylog. It uses @chax-at/gelf-client under the hood.

new GelfLogDrain(new SecureTCPTransport({
    host: GELF_HOST,
    port: GELF_PORT,
    ca: GELF_SERVER_CA_CERT, // CA certificate string or buffer
    cert: GELF_CLIENT_CERT,  // Client certificate string or buffer
    key: GELF_CLIENT_KEY,    // CLient key string or buffer
}));

new GelfLogDrain(new TCPTransport({
    host: GELF_HOST,
    port: GELF_PORT,
}));

new GelfLogDrain(new UDPTransport({
    host: GELF_HOST,
    port: GELF_PORT,
    timeout: GELF_TIMEOUT,   // optional timeout (default 1000ms)
    protocol: GELF_PROTOCOL, // udp4 (default) or udp6
}));

FilesystemLogDrain

The FilesystemLogDrain logs messages to a file on the filesystem.

new FilesystemLogDrain({
    fileName? : string; // optional filename (default log.txt)
    formatFunction? : LogFormatFunction; // optional formatting function for the logged message
    indentation? : number; // optional indentation for nested newlines (default 4)
    logAttributes? : boolean; // whether to log embedded attributes (default true)
    outDir: string; // the path of the directory the log file will be created
    separateWithEmptyLine? : boolean; // whether to add an additional newline after each log message to improve readability (default false)
});

OpenTelemetryLogDrain

The OpenTelemetryLogDrain logs messages via OpenTelemetry.

First, install the necessary packages in your project:

npm i "@opentelemetry/sdk-node" "@opentelemetry/api" "@opentelemetry/sdk-logs" "@opentelemetry/exporter-logs-otlp-proto"

then use it the following way

import {NodeSDK} from "@opentelemetry/sdk-node";
import {SimpleLogRecordProcessor} from "@opentelemetry/sdk-logs";
import {logs} from '@opentelemetry/api-logs';
import {OTLPLogExporter} from "@opentelemetry/exporter-logs-otlp-proto";

import LogSink, {LogLevel, OpenTelemetryLogDrain} from '@chax-at/log-sink';

const exporter = new OTLPLogExporter({
    //url: defaults to 'http://localhost:4318/v1/logs',
});

const sdk = new NodeSDK({
    logRecordProcessor: new SimpleLogRecordProcessor(exporter),
});
sdk.start();

const logger = logs.getLoggerProvider().getLogger("default");
LogSink.registerDrain(new OpenTelemetryLogDrain(logger), {
    enabled: true,
    minLevel: LogLevel.Error,
    maxLevel: LogLevel.Debug
});

LogSink.info("This is a log");

More info can be found in the OpenTelemetry info or the official open-telemetry documentation.

版本与发布记录

@chax-at/log-sink 共发布 10 个版本,首次发布于 2022/02/10;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.0.2latest2025/08/291.2 年前
2.0.12025/05/081.5 年前
2.0.0-alpha.1next2025/05/081.5 年前
2.0.02024/06/112 年前
1.1.02024/05/172 年前
1.0.02023/10/233 年前

关于 @chax-at/log-sink 的常见问题

@chax-at/log-sink 是什么?

A Log Service

如何安装 @chax-at/log-sink?

在项目目录运行 npm install @chax-at/log-sink,或使用 pnpm add / yarn add / bun add。

@chax-at/log-sink 支持 TypeScript 吗?

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

@chax-at/log-sink 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@chax-at/log-sink 可以商用吗?

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

@chax-at/log-sink 的下载量有多少?

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

@chax-at/log-sink 还在维护吗?

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