Logo Logging

Logging

Tổ chứcPhổ biến
EpicenterHQ
logging

Use for wellcrafted/logger, logger sinks, library diagnostics, typed logging, background errors, durable host logs, or replacing console.* in library code.

Tổng quan

Nhà phát hànhEpicenterHQ
Kho mãepicenter
Tên kỹ nănglogging
Sao
4.8K
Bản fork
386
Tệp đi kèm
Chỉ có hướng dẫn
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Đầy đủ trong hướng dẫn

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được EpicenterHQ công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Logging trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/EpicenterHQ/epicenter/tree/main/.agents/skills/logging
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/EpicenterHQ/epicenter.git /tmp/epicenter
mkdir -p .claude/skills
cp -r /tmp/epicenter/.agents/skills/logging .claude/skills/logging
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Logging trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Logging ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Logging không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Workspace Logger

Structured, level-keyed, field-oriented logging for library code. Modeled on Rust's tracing. Completes the defineErrors story: errors are structured data; level lives at the call site.

Ground API and behavior claims in the official wellcrafted-dev/wellcrafted source and logger declarations for Epicenter's installed version. Ground call site examples in current Epicenter code.

Where it lives

All of it ships from wellcrafted/logger: createLogger, consoleSink, memorySink, composeSinks, and the types. Runtime-agnostic, browser-safe. No file sink in-process: durability is a host concern (shell redirect, systemd journal, Cloudflare tail). The library emits to consoleSink; the operator decides where stdout/stderr go.

Quickstart

ts
import { createLogger } from 'wellcrafted/logger';

const log = createLogger('markdown-materializer'); // defaults to consoleSink

log.info('materializer ready');

const result = await writeProjection();
if (result.error !== null) log.warn(result.error);

The 5 levels

trace | debug | info | warn | error. No fatal: process termination is the app's call, not the library's.

LevelSignatureUse for
trace(message, data?)Per-token / per-message noise; off in prod
debug(message, data?)Internal state transitions (handshakes, cache loads)
info(message, data?)Lifecycle events (connected, loaded, flushed)
warn(err)Recoverable failure: retry, fallback, partial result
error(err)Unrecoverable at this layer; the operation has given up

Shape split is intentional. warn / error take a typed error unary: the variant carries message, name, and captured fields. trace / debug / info are free-form because free-running diagnostic events don't need enumeration.

Native Error also satisfies the logger's structural { name, message } contract. This is intentional for migration and exception boundaries; prefer a tagged variant when the layer owns a stable failure vocabulary.

Level is a call-site decision, not a variant property

ts
// Right: same error, different levels in different contexts
log.warn(SyncError.ConnectionFailed({ cause }));  // inside retry loop
log.error(SyncError.ConnectionFailed({ cause })); // last attempt, giving up

Do NOT attach a severity to defineErrors variants. That's miette's pattern; tracing, log, and every production Rust logger put level on the call. Context-dependent data belongs at the context.

The dominant call-site shape

In epicenter, the typical pattern is branch on the Result, log inside the branch, then take action. The Result's data is usually needed on the Ok branch, so a chain combinator wouldn't earn its keep:

ts
const walResult = trySync({
  try: () => db.query('PRAGMA journal_mode = WAL').get(),
  catch: (cause) => SqliteWriterError.PragmaSetupFailed({ pragma: 'WAL', cause }),
});
if (walResult.error !== null) {
  log.warn(walResult.error);
} else if (walResult.data !== 'wal') {
  log.warn(SqliteWriterError.WalSilentFallback({ actualMode: walResult.data }));
}

You can also mint-and-log a tagged variant directly inside a .catch tail when there's no Result to branch on:

ts
}).catch((cause) => {
  log.warn(MaterializerWriteError.TableWriteFailed({ tableName, cause }));
});

Two anti-patterns, both already paid for

grep -rn "consoleSink({" src/ and grep -rn "log\.\(warn\|error\)(new Error" src/ before adding either.

Do not call a sink directly

Sinks take a raw LogEvent, which constrains nothing. createLogger is what binds the Logger type, and the Logger type is the only thing enforcing that warn/error are unary over a LoggableError. Reaching past the factory to consoleSink({ ts, level, source, message, data }) is not a shortcut to the same behavior: it is opting out of the contract.

Whispering did exactly this and grew a parallel log whose warn(error: Error, data?: unknown) silently dropped the error object whenever a caller passed the second argument. Nothing caught it, because nothing had promised anything. Import createLogger; import consoleSink only to compose it into a sink you pass to createLogger.

Do not mint a new Error at a log call site

log.warn(new Error('X failed', { cause })) type-checks, because native Error satisfies LoggableError structurally. That escape hatch exists for migrating old catch (e) { console.warn(e) } sites, not for authoring new ones. A hand-built Error gives the sink a message string and no name worth filtering on, and the phrasing lives at the call site where the next similar failure will phrase it slightly differently.

Mint a defineErrors variant instead, owned by the module that owns the failure.

The tell to watch for: a boundary that types a failure callback as (cause: unknown) and ships no vocabulary with it. Every implementer must then invent a message, and new Error is the shortest way. If you declare such a callback, export the variants for it from the same file:

ts
export const WhisperingBackgroundError = defineErrors({
  AppFailed: ({ cause }: { cause: unknown }) => ({
    message: 'Whispering app background work failed',
    cause,
  }),
});

export type WhisperingAppOptions = {
  reportBackgroundError(cause: unknown): void;
};

Implementers then name a failure rather than describing one:

ts
reportBackgroundError: (cause) => log.warn(WhisperingBackgroundError.AppFailed({ cause }))

Log-only variants are not public API

Minting a variant is not the same as publishing one. Two kinds:

Returned in a ResultOnly logged
Who sees itConsumers, who branch on .nameA log sink
Export it?Yes; renaming a variant is a breaking changeNo, const at module scope
ExamplesReplicaError, DocumentPullError, DataReadError, TransportProtocolErrorSyncSupervisorError, BrowserWorkerError, ObservationCarrierError

Exporting a log-only set publishes a name no one can import for a reason and freezes a string you should stay free to reword. packages/app and packages/lens keep theirs private for exactly this; only errors that leave in a Result are in the published failure surface. Export a log-only set solely when a second file in the same package logs the same failure, and even then, only within the package.

Name the variant key for the log line, not for the set. defineErrors stamps name from the key alone; the const you assign the set to never reaches the sink. createLogger's source supplies the namespace, so [data/sync] { name: 'StatusSubscriberThrew' } reads fine and the key stays short.

Prefer a field over interpolation. new Error(`could not ${what}`) produces a message no two calls share. ContainedStepFailed({ step: what, cause }) gives one constant message and a structured step.

When the consumer is not a Logger

log.warn(Variant({ cause })) passes the Err wrapper, and createLogger unwraps it. A hand-narrowed reporter type does not:

ts
// packages/lens: deliberately not `Logger`, so published declarations never
// reach AsyncDisposable and never dictate a consumer's logging stack
export type InvalidationErrorReporter = { error(error: unknown): void };

Anything reaching a reporter like this must be plain readable data, so extract the error payload at the call site: log.error(ObservationCarrierError.FrameNotText().error). A stranger's { error(e) { ... } } then reads name, message, and cause off the object instead of finding a wrapper.

Sinks

A sink is ((event) => void) & Partial<AsyncDisposable>: a callable with optional resource cleanup.

ts
import {
  createLogger,
  consoleSink,    // default; routes to console[level]
  memorySink,     // for tests; returns { sink, events }
  composeSinks,   // fan out to multiple sinks
} from 'wellcrafted/logger';

Durability is the host's job

For a long-running daemon or CLI that needs durable logs, the library still emits to consoleSink; the operator decides where the stream goes:

bash
bun run start                          # dev: console
bun run start 2>> ~/.app/app.jsonl     # ad-hoc file capture
systemd-run --user bun run start       # journal (structured queries via journalctl)

This used to be jsonlFileSink; that primitive was removed because owning a file writer in-process bought complexity (backpressure, dispose semantics, error fallbacks) that shell redirection already solves.

composeSinks(...): fan out

ts
const sink = composeSinks(consoleSink, myCustomSink);
const log = createLogger('source', sink);

composeSinks forwards disposal to members that implement it (via sink[Symbol.asyncDispose]?.()). consoleSink is a no-op on dispose; stateful sinks flush and close.

memorySink(): for tests

ts
const { sink, events } = memorySink();
const log = createLogger('test', sink);
log.warn(MyError.Thing({ cause: new Error('boom') }));
expect(events).toHaveLength(1);
expect(events[0]).toMatchObject({ level: 'warn', source: 'test' });

Do NOT assert on console.* output. Inject a memorySink and inspect the event array.

DI, not globals

No module-level logger registry. No setDefaultLogger(). Each attach primitive takes an optional log?: Logger option and defaults to createLogger(<source>) (console sink). Caller wires sinks explicitly.

ts
const markdown = attachMarkdownExport(workspace, { dir, tables, log });
const sqlite = attachBunSqliteMaterializer(workspace, { filePath, log });
const collaboration = openCollaboration(workspace.ydoc, {
	url,
	openWebSocket,
	onReconnectSignal,
	log,
});

Share one sink across loggers when you build a custom one:

ts
const sink = composeSinks(consoleSink, myCustomSink);
const markdown = attachMarkdownExport(workspace, {
	dir,
	tables,
	log: createLogger('workspace/markdown', sink),
});
const sqlite = attachBunSqliteMaterializer(workspace, {
	filePath,
	log: createLogger('workspace/sqlite', sink),
});

Browser

The whole surface is pure JS and browser-safe.

Event shape

Every sink receives:

ts
type LogEvent = {
  ts:      number;    // epoch millis
  level:   LogLevel;  // 'trace' | 'debug' | 'info' | 'warn' | 'error'
  source:  string;    // from createLogger()
  message: string;    // human text: for warn/error, inherited from the typed error
  data?:   unknown;   // the typed error for warn/error; free-form for info/debug/trace
};

Custom sinks that serialize for the wire should convert ts to ISO-8601 and flatten native Error instances (otherwise they JSON.stringify to {}).

See also

  • error-handling skill: trySync/tryAsync patterns and the error variants reference for the typed failures the logger consumes
  • tauri's Rust command errors reference: typed failures that cross IPC
  • tapErr (from wellcrafted/result): Result-chain combinator that logs on the Err branch and passes the Result through. Rare in epicenter, since most call sites branch on result.error directly to use the data on the Ok branch. Reach for it only when the Result flows out of the function in a .then(...) chain.

Câu hỏi thường gặp

Kỹ năng AI Logging làm được gì?

Use for wellcrafted/logger, logger sinks, library diagnostics, typed logging, background errors, durable host logs, or replacing console.* in library code.

Vì sao nên dùng Logging trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Logging là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Logging trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/EpicenterHQ/epicenter/tree/main/.agents/skills/logging. TypingMind đọc tệp SKILL.md và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Logging?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Logging với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Logging với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Logging có miễn phí không?

Kỹ năng này được EpicenterHQ phát hành trên GitHub. Hãy xem điều khoản giấy phép trong kho mã. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇