winston-sqlite-wal-batch
v0.1.0
Published
Production-ready Winston transport with SQLite WAL batch writes for multi-bot shared logging.
Downloads
95
Maintainers
Readme
winston-sqlite-wal-batch
面向多 bot 场景的 Winston Transport:使用 SQLite(WAL) 做批量日志写入与分析查询。
适用场景
- 同一台机器跑多个 bot,希望共享一个日志库。
- 需要 SQL 分析日志,但不想引入额外日志服务。
- VPS 资源有限(2 vCPU / 4GB)且强调稳定运行。
特性
- 批量写入:内存队列 + 单事务批量
INSERT - WAL 模式:
journal_mode=WAL+synchronous=NORMAL - 多 bot 共享:统一
bot_logs表,按bot_id分析 - 低资源保护:队列上限 + 优先保留高等级日志
- 内置维护:按保留天数清理 +
wal_checkpoint(PASSIVE) - 内置分析 API:最近日志、等级聚合、错误 Top
安装
npm install winston-sqlite-wal-batch winston接入示例
import winston from "winston";
import { SqliteWinstonBatchTransport } from "winston-sqlite-wal-batch";
const logger = winston.createLogger({
level: "info",
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.Console(),
new SqliteWinstonBatchTransport({
// dbPath 可省略,默认 ~/bot-logs/shared-logs.db
botId: process.env.BOT_ID ?? "bot-unknown",
source: "vps-ts-bot",
flushIntervalMs: 500,
batchSize: 200,
maxQueueSize: 10000,
retentionDays: 14,
maintenanceIntervalMs: 60000,
}),
],
});
logger.info("bot started", { event: "startup" });
logger.error("execution failed", { event: "exec", execKey: "abc:123", err: "timeout" });多 bot 共用同一 SQLite
所有 bot 只要 dbPath 指向同一文件即可,例如:
~/bot-logs/shared-logs.db
每个 bot 需要设置不同 botId,例如:
bot-abot-b
分析查询示例
import { openSharedLogDatabaseReadOnly, queryLevelSummary, queryTopErrorMessages } from "winston-sqlite-wal-batch";
const db = openSharedLogDatabaseReadOnly(`${process.env.HOME}/bot-logs/shared-logs.db`);
const levelSummary = queryLevelSummary(db, {
botId: "bot-a",
fromMs: Date.now() - 60 * 60 * 1000,
bucketMs: 60_000,
});
const topErrors = queryTopErrorMessages(db, {
botId: "bot-a",
fromMs: Date.now() - 24 * 60 * 60 * 1000,
limit: 20,
});
console.log(levelSummary.length, topErrors.length);
db.close();建议的 .env 配置(示例)
BOT_ID=bot-a
LOG_SQLITE_PATH=~/bot-logs/shared-logs.db说明:本包不读取私钥、token 等敏感配置。敏感信息应仅由 bot 自身 .env 管理。
对外 API
SqliteWinstonBatchTransportopenSharedLogDatabaseopenSharedLogDatabaseReadOnlyrunRetentionCleanuprunWalCheckpointqueryRecentLogsqueryLevelSummaryqueryTopErrorMessages
发布
npm run build
npm run pack:dry-run
npm login --registry https://registry.npmjs.org
npm run publish:npm如果包名已被占用,请先修改 package.json 的 name 后再发布。
