Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

feat(collector): LOG_LEVEL env to control log verbosity (#80)

luoleifa9ed96dbf8a
diff --git a/.env.example b/.env.example
index f9ff37b..77ffab5 100644
--- a/.env.example
+++ b/.env.example
@@ -72,6 +72,10 @@ WS_EXTERNAL_PORT=3002
# API_PORT=3001
# COLLECTOR_WS_PORT=3002
+# 采集器日志级别:error / warn / info / debug(大小写不敏感,默认 info)
+# console.error 始终输出,不受日志级别影响
+# LOG_LEVEL=info
+
# Agent 判定离线的心跳超时,后端列表/健康检查/手动测试共用(毫秒,最小 15000;默认 30 秒心跳 × 3,容忍上报延迟)
# 设置在采集器进程的环境中
# AGENT_HEARTBEAT_TIMEOUT_MS=90000
diff --git a/README.en.md b/README.en.md
index 2281cc2..2918467 100644
--- a/README.en.md
+++ b/README.en.md
@@ -419,6 +419,7 @@ The script will automatically detect and suggest available ports.
| `API_URL` | `http://localhost:3001` | Next.js `/api` rewrite target (mainly source/custom builds) | API listen address changed |
| `COOKIE_SECRET` | auto-generated | Cookie signing secret; if not fixed, sessions can be invalidated after restart when data dir is not persisted | Strongly recommended in production |
| `AGENT_HEARTBEAT_TIMEOUT_MS` | `90000` | How long (ms, minimum `15000`) an agent may go without a heartbeat/report before it is shown offline (backend list, health checks, manual test). Defaults to 3 × the agent's 30s heartbeat interval | Agents flap online/offline on slow links |
+| `LOG_LEVEL` | `info` | Collector log level: `error`, `warn`, `info`, or `debug` (case-insensitive); `console.error` is always emitted | Reduce collector log volume or enable debug output |
| `BACKEND_TLS_INSECURE` | empty | Set to `1` to skip TLS certificate verification for gateway APIs only (Surge `http-api-tls`, mihomo `external-controller-tls` with self-signed certs). Logs a warning at startup | Gateway uses HTTPS with a self-signed / IP-mismatched certificate |
| `GEOIP_LOOKUP_PROVIDER` | `online` | IP geolocation source (`online` / `local`) | Default to local MMDB lookup |
| `GEOIP_ONLINE_API_URL` | `https://api.ipinfo.es/ipinfo` | Online IP geolocation API endpoint (must be compatible with `ipinfo.my` response schema) | Set only when you deploy a compatible endpoint |
diff --git a/README.md b/README.md
index 9cc79f1..0088e2c 100644
--- a/README.md
+++ b/README.md
@@ -419,6 +419,7 @@ The script will automatically detect and suggest available ports.
| `API_URL` | `http://localhost:3001` | Next.js `/api` rewrite target (mainly source/custom builds) | API listen address changed |
| `COOKIE_SECRET` | auto-generated | Cookie signing secret; if not fixed, sessions can be invalidated after restart when data dir is not persisted | Strongly recommended in production |
| `AGENT_HEARTBEAT_TIMEOUT_MS` | `90000` | How long (ms, minimum `15000`) an agent may go without a heartbeat/report before it is shown offline (backend list, health checks, manual test). Defaults to 3 × the agent's 30s heartbeat interval | Agents flap online/offline on slow links |
+| `LOG_LEVEL` | `info` | Collector log level: `error`, `warn`, `info`, or `debug` (case-insensitive); `console.error` is always emitted | Reduce collector log volume or enable debug output |
| `BACKEND_TLS_INSECURE` | empty | Set to `1` to skip TLS certificate verification for gateway APIs only (Surge `http-api-tls`, mihomo `external-controller-tls` with self-signed certs). Logs a warning at startup | Gateway uses HTTPS with a self-signed / IP-mismatched certificate |
| `GEOIP_LOOKUP_PROVIDER` | `online` | IP geolocation source (`online` / `local`) | Default to local MMDB lookup |
| `GEOIP_ONLINE_API_URL` | `https://api.ipinfo.es/ipinfo` | Online IP geolocation API endpoint (must be compatible with `ipinfo.my` response schema) | Set only when you deploy a compatible endpoint |
diff --git a/apps/collector/src/index.ts b/apps/collector/src/index.ts
index 53183dc..7de2c19 100644
--- a/apps/collector/src/index.ts
+++ b/apps/collector/src/index.ts
@@ -1,17 +1,7 @@
-import { config } from 'dotenv';
+import './shared/utils/initialize-logger.js';
import path from 'path';
-import fs from 'fs';
import { isAgentBackendUrl } from '@neko-master/shared';
-// Load .env.local if it exists (takes precedence over .env, but not shell)
-const envLocalPath = path.join(process.cwd(), '.env.local');
-if (fs.existsSync(envLocalPath)) {
- config({ path: envLocalPath, quiet: true });
-}
-
-// Load .env (defaults)
-config({ quiet: true });
-
import { StatsDatabase, BackendConfig } from './modules/db/db.js';
import { createCollector, GatewayCollector } from './modules/collector/gateway.collector.js';
import { createSurgeCollector, SurgeCollector } from './modules/collector/surge.collector.js';
diff --git a/apps/collector/src/shared/utils/initialize-logger.ts b/apps/collector/src/shared/utils/initialize-logger.ts
new file mode 100644
index 0000000..27aba5c
--- /dev/null
+++ b/apps/collector/src/shared/utils/initialize-logger.ts
@@ -0,0 +1,14 @@
+import { config } from 'dotenv';
+import path from 'path';
+import fs from 'fs';
+import { applyLogLevel } from './logger.js';
+
+// Load .env.local if it exists (takes precedence over .env, but not shell).
+const envLocalPath = path.join(process.cwd(), '.env.local');
+if (fs.existsSync(envLocalPath)) {
+ config({ path: envLocalPath, quiet: true });
+}
+
+// Load .env (defaults) before applying the level and importing collector modules.
+config({ quiet: true });
+applyLogLevel();
diff --git a/apps/collector/src/shared/utils/logger.test.ts b/apps/collector/src/shared/utils/logger.test.ts
new file mode 100644
index 0000000..6e3bfba
--- /dev/null
+++ b/apps/collector/src/shared/utils/logger.test.ts
@@ -0,0 +1,95 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const methods = ['debug', 'log', 'info', 'warn', 'error'] as const;
+const originalConsole = { ...console };
+const levelCases = [
+ { level: 'debug', expected: [1, 1, 1, 1, 1] },
+ { level: 'info', expected: [0, 1, 1, 1, 1] },
+ { level: 'warn', expected: [0, 0, 0, 1, 1] },
+ { level: 'error', expected: [0, 0, 0, 0, 1] },
+];
+
+describe('applyLogLevel', () => {
+ let spies: ReturnType<typeof vi.spyOn>[];
+
+ beforeEach(() => {
+ vi.resetModules();
+ vi.stubEnv('LOG_LEVEL', undefined);
+ spies = methods.map((method) => vi.spyOn(console, method).mockImplementation(() => {}));
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ for (const method of methods) console[method] = originalConsole[method];
+ vi.unstubAllEnvs();
+ });
+
+ function expectForwarding(expected: number[]): void {
+ const detail = { context: 'logger test' };
+ methods.forEach((method, index) => {
+ console[method]('message', detail);
+ expect(spies[index]).toHaveBeenCalledTimes(expected[index]);
+ if (expected[index]) expect(spies[index]).toHaveBeenLastCalledWith('message', detail);
+ });
+ expect(console.error).toBe(spies[4]);
+ }
+
+ it.each(levelCases)('forwards the expected methods at $level', async ({ level, expected }) => {
+ const { applyLogLevel } = await import('./logger.js');
+ applyLogLevel(level);
+ expectForwarding(expected);
+ });
+
+ it.each(levelCases)('accepts uppercase $level', async ({ level, expected }) => {
+ const { applyLogLevel } = await import('./logger.js');
+ applyLogLevel(level.toUpperCase());
+ expectForwarding(expected);
+ });
+
+ it('accepts mixed case', async () => {
+ const { applyLogLevel } = await import('./logger.js');
+ applyLogLevel('WaRn');
+ expectForwarding([0, 0, 0, 1, 1]);
+ });
+
+ it('defaults to info when LOG_LEVEL is unset', async () => {
+ const { applyLogLevel } = await import('./logger.js');
+ applyLogLevel();
+ expectForwarding([0, 1, 1, 1, 1]);
+ });
+
+ it('reads LOG_LEVEL when no argument is provided', async () => {
+ const { applyLogLevel } = await import('./logger.js');
+ vi.stubEnv('LOG_LEVEL', 'ERROR');
+ applyLogLevel();
+ expectForwarding([0, 0, 0, 0, 1]);
+ });
+
+ it.each(['verbose', ''])('warns once and falls back to info for "%s"', async (level) => {
+ const { applyLogLevel } = await import('./logger.js');
+ applyLogLevel(level);
+ expect(spies[3]).toHaveBeenCalledExactlyOnceWith(
+ `[Logger] Unknown LOG_LEVEL=${level}, falling back to info`,
+ );
+ vi.clearAllMocks();
+ expectForwarding([0, 1, 1, 1, 1]);
+ });
+
+ it('restores methods when verbosity increases', async () => {
+ const { applyLogLevel } = await import('./logger.js');
+ applyLogLevel('error');
+ applyLogLevel('debug');
+ expectForwarding([1, 1, 1, 1, 1]);
+ });
+
+ it('still warns once for an invalid level after error', async () => {
+ const { applyLogLevel } = await import('./logger.js');
+ applyLogLevel('error');
+ applyLogLevel('invalid');
+ expect(spies[3]).toHaveBeenCalledExactlyOnceWith(
+ '[Logger] Unknown LOG_LEVEL=invalid, falling back to info',
+ );
+ vi.clearAllMocks();
+ expectForwarding([0, 1, 1, 1, 1]);
+ });
+});
diff --git a/apps/collector/src/shared/utils/logger.ts b/apps/collector/src/shared/utils/logger.ts
new file mode 100644
index 0000000..4991258
--- /dev/null
+++ b/apps/collector/src/shared/utils/logger.ts
@@ -0,0 +1,32 @@
+/* eslint-disable no-console -- This module intentionally replaces console methods to control verbosity. */
+
+const levels = ['error', 'warn', 'info', 'debug'];
+const methods = [
+ ['debug', 3],
+ ['log', 2],
+ ['info', 2],
+ ['warn', 1],
+] as const;
+const originalMethods = methods.map(([method, severity]) => ({
+ method,
+ severity,
+ original: console[method],
+}));
+const noop = (): void => {};
+
+export function applyLogLevel(level = process.env.LOG_LEVEL): void {
+ // Restore methods so repeated calls can increase verbosity and always warn.
+ for (const { method, original } of originalMethods) {
+ console[method] = original;
+ }
+
+ let threshold = levels.indexOf((level ?? 'info').toLowerCase());
+ if (threshold === -1) {
+ console.warn(`[Logger] Unknown LOG_LEVEL=${level}, falling back to info`);
+ threshold = levels.indexOf('info');
+ }
+
+ for (const { method, severity } of originalMethods) {
+ if (severity > threshold) console[method] = noop;
+ }
+}
diff --git a/docker-compose.yml b/docker-compose.yml
index db575e2..35855f7 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -14,6 +14,7 @@ services:
- ./geoip:/app/data/geoip:ro
environment:
- NODE_ENV=production
+ - LOG_LEVEL=${LOG_LEVEL:-info}
- WEB_PORT=3000
- API_PORT=3001
- COLLECTOR_WS_PORT=3002