> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch34-infrastructure/34.1-logging-system.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 34.1 Logging System

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~48k tokens, Output \~6k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

The logging system is the "black box" of the OpenClaw runtime—it records every Gateway request, every channel connection state, and the complete history of every Agent invocation. OpenClaw builds a dual-track logging architecture based on the tslog library: file logs (structured JSON) for post-mortem analysis, and console logs (colored text) for real-time monitoring.

## 34.1.1 Logging Framework: tslog (`src/logger.ts`)

### Introduction to tslog

> **Sidebar — tslog**
>
> tslog is a TypeScript-native logging library characterized by zero dependencies, type safety, and support for structured logging. Unlike popular logging libraries like winston or pino, tslog's design philosophy is "what you see is what you get"—the field types of log objects are determined at compile time. OpenClaw uses tslog in `hidden` mode (no ANSI output), forwarding logs to files through custom transports.

### Log Levels

OpenClaw defines seven log levels, arranged from highest to lowest severity:

```typescript
// src/logging/levels.ts
export const ALLOWED_LOG_LEVELS = [
  "silent",  // No logs output
  "fatal",   // Fatal error (process will exit)
  "error",   // Error
  "warn",    // Warning
  "info",    // Information (default level)
  "debug",   // Debug (enabled in verbose mode)
  "trace",   // Trace (most detailed)
] as const;
```

Internally, tslog uses numbers to represent levels: `fatal=0, error=1, warn=2, info=3, debug=4, trace=5`. `silent` maps to `+∞`, meaning no logs can pass this threshold.

### Logger Factory and Rolling Logs

`getLogger()` is the unified entry point for obtaining a file logger instance, using lazy initialization and caching:

```typescript
// src/logging/logger.ts (simplified)
export const DEFAULT_LOG_DIR = "/tmp/openclaw";

export function getLogger(): TsLogger<LogObj> {
  const settings = resolveSettings();
  const cachedLogger = loggingState.cachedLogger;
  // Rebuild logger when settings change
  if (!cachedLogger || settingsChanged(loggingState.cachedSettings, settings)) {
    loggingState.cachedLogger = buildLogger(settings);
    loggingState.cachedSettings = settings;
  }
  return loggingState.cachedLogger;
}
```

Log files use a **daily rolling** strategy with filename format `openclaw-YYYY-MM-DD.log`:

```typescript
function defaultRollingPathForToday(): string {
  const today = formatLocalDate(new Date()); // "2026-02-18"
  return path.join(DEFAULT_LOG_DIR, `openclaw-${today}.log`);
}
```

Each time a new Logger is created, old log files older than 24 hours are automatically cleaned up:

```typescript
function pruneOldRollingLogs(dir: string): void {
  const cutoff = Date.now() - MAX_LOG_AGE_MS; // 24h
  for (const entry of fs.readdirSync(dir)) {
    if (entry.name.startsWith("openclaw-") && entry.name.endsWith(".log")) {
      const stat = fs.statSync(fullPath);
      if (stat.mtimeMs < cutoff) {
        fs.rmSync(fullPath, { force: true });
      }
    }
  }
}
```

> The log directory is fixed at `/tmp/openclaw` (on macOS, `os.tmpdir()` may return a user-specific random path, causing the "Open Logs" button in the Debug UI to fail).

### File Log Transport

Each log line is appended to the file in JSON format:

```typescript
logger.attachTransport((logObj: LogObj) => {
  const time = logObj.date?.toISOString?.() ?? new Date().toISOString();
  const line = JSON.stringify({ ...logObj, time });
  fs.appendFileSync(settings.file, `${line}\n`, { encoding: "utf8" });
});
```

Example log line:

```json
{"0":"gateway started","_meta":{"name":"openclaw","date":"2026-02-18T08:30:00.123Z"},"time":"2026-02-18T08:30:00.123Z"}
```

### External Transport Extension

The logging system supports registering external transports, allowing plugins to forward logs to third-party services:

```typescript
export function registerLogTransport(transport: LogTransport): () => void {
  externalTransports.add(transport);
  // If logger already exists, attach immediately
  if (loggingState.cachedLogger) {
    attachExternalTransport(loggingState.cachedLogger, transport);
  }
  // Return unregister function
  return () => { externalTransports.delete(transport); };
}
```

Exceptions in transport callbacks are silently swallowed—**logging must never block the main flow**.

### Pino Compatibility Adapter

The WhatsApp library Baileys expects a pino-style logging interface. `toPinoLikeLogger` adapts a tslog Logger to the pino interface:

```typescript
export function toPinoLikeLogger(logger: TsLogger<LogObj>, level: LogLevel): PinoLikeLogger {
  return {
    level,
    child: (bindings) => toPinoLikeLogger(logger.getSubLogger({ name: JSON.stringify(bindings) }), level),
    trace: (...args) => logger.trace(...args),
    debug: (...args) => logger.debug(...args),
    // ... info, warn, error, fatal
  };
}
```

## 34.1.2 Log Levels and Output (`src/logging/` directory)

### Dual-Track Output Architecture

OpenClaw's log output is divided into two independent tracks:

```
Application Code
    │
    ├─── File Track (File Logger)
    │    ├── Level filtering: controlled by logging.level config (default info)
    │    ├── Format: JSON, one line per entry
    │    └── Target: /tmp/openclaw/openclaw-YYYY-MM-DD.log
    │
    └─── Console Track (Console Logger)
         ├── Level filtering: controlled by logging.consoleLevel config (auto-elevated to debug in verbose mode)
         ├── Format: three styles - pretty / compact / json
         └── Target: stdout (or stderr in RPC mode)
```

### Console Output Styles

| Style     | Trigger Condition          | Format                                                                |
| --------- | -------------------------- | --------------------------------------------------------------------- |
| `pretty`  | TTY terminal (default)     | `08:30:00 [discord] colored message`                                  |
| `compact` | Non-TTY or explicit config | `2026-02-18T08:30:00.123Z [discord] message`                          |
| `json`    | Explicit config            | `{"time":"...","level":"info","subsystem":"discord","message":"..."}` |

### Subsystem Logger

OpenClaw's subsystem logging is the most elegant part of the logging system—it creates independent prefixed logger instances for each module (such as `discord`, `telegram`, `gateway/ws`):

```typescript
// src/logging/subsystem.ts (simplified)
export function createSubsystemLogger(subsystem: string): SubsystemLogger {
  const emit = (level: LogLevel, message: string, meta?: Record<string, unknown>) => {
    // 1. Write to file (always write, subject to file level filtering)
    logToFile(getFileLogger(), level, message, meta);

    // 2. Console level filtering
    if (!shouldLogToConsole(level, consoleSettings)) return;

    // 3. Subsystem filter (can be configured to show only specific subsystems)
    if (!shouldLogSubsystemToConsole(subsystem)) return;

    // 4. Format and output
    const line = formatConsoleLine({ level, subsystem, message, style });
    writeConsoleLine(level, line);
  };

  return {
    subsystem,
    trace: (msg, meta) => emit("trace", msg, meta),
    debug: (msg, meta) => emit("debug", msg, meta),
    info:  (msg, meta) => emit("info",  msg, meta),
    warn:  (msg, meta) => emit("warn",  msg, meta),
    error: (msg, meta) => emit("error", msg, meta),
    fatal: (msg, meta) => emit("fatal", msg, meta),
    raw: (msg) => { /* output directly without formatting */ },
    child: (name) => createSubsystemLogger(`${subsystem}/${name}`),
  };
}
```

Subsystem names support hierarchical structure (`"gateway/ws"`, `"agent/embedded"`), and the `child()` method creates child logger instances.

### Subsystem Color Assignment

In console output, each subsystem uses a different color for easy distinction:

```typescript
const SUBSYSTEM_COLORS = ["cyan", "green", "yellow", "blue", "magenta", "red"] as const;

function pickSubsystemColor(color: ChalkInstance, subsystem: string): ChalkInstance {
  // Specific subsystems have fixed color overrides
  const override = SUBSYSTEM_COLOR_OVERRIDES[subsystem];
  if (override) return color[override];
  // Others use name hash for assignment
  let hash = 0;
  for (let i = 0; i < subsystem.length; i++) {
    hash = (hash * 31 + subsystem.charCodeAt(i)) | 0;
  }
  return color[SUBSYSTEM_COLORS[Math.abs(hash) % SUBSYSTEM_COLORS.length]];
}
```

### Console Capture — Console Hijacking

`enableConsoleCapture()` is a critical step in the CLI startup flow—it hijacks `console.log/info/warn/error/debug/trace`, writing all console output simultaneously to the file log:

```typescript
export function enableConsoleCapture(): void {
  if (loggingState.consolePatched) return; // idempotent
  loggingState.consolePatched = true;

  const original = {
    log: console.log,
    info: console.info,
    // ...
  };

  const forward = (level: LogLevel, orig: Function) => (...args: unknown[]) => {
    const formatted = util.format(...args);
    if (shouldSuppressConsoleMessage(formatted)) return; // suppress noise

    // Write to file log
    getLoggerLazy()[level](formatted);

    // Write back to console (or stderr)
    if (loggingState.forceConsoleToStderr) {
      process.stderr.write(`${formatted}\n`);
    } else {
      orig.apply(console, args);
    }
  };

  console.log = forward("info", original.log);
  console.warn = forward("warn", original.warn);
  // ...
}
```

Special handling:

* **Noise suppression**: In non-verbose mode, high-frequency messages like `"Closing session:"` and `"Opening session:"` are silenced
* **EPIPE handling**: Pipe break (EPIPE) errors are silently swallowed rather than crashing the process
* **RPC/JSON mode**: `routeLogsToStderr()` redirects all console output to stderr, keeping stdout clean (for `--json` output)
* **Timestamp prefix**: Optionally auto-adds timestamp prefix (excluding already-timestamped and JSON content)

### Sensitive Information Redaction

The logging system has a built-in regex-driven sensitive information redaction engine:

```typescript
// src/logging/redact.ts
const DEFAULT_REDACT_PATTERNS: string[] = [
  // ENV-style: API_KEY=sk-abc123...
  String.raw`\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD)\b\s*[=:]\s*(["']?)([^\s"'\\]+)\1`,
  // JSON fields: "apiKey": "..."
  String.raw`"(?:apiKey|token|secret|password|accessToken)"\s*:\s*"([^"]+)"`,
  // CLI flags: --api-key sk-abc...
  String.raw`--(?:api[-_]?key|token|secret)\s+(["']?)([^\s"']+)\1`,
  // Bearer tokens
  String.raw`\bBearer\s+([A-Za-z0-9._\-+=]{18,})\b`,
  // Common prefixes: sk-..., ghp_..., xox-..., etc.
  String.raw`\b(sk-[A-Za-z0-9_-]{8,})\b`,
  String.raw`\b(ghp_[A-Za-z0-9]{20,})\b`,
  // ... more patterns
];
```

Redaction strategy: preserve the first 6 and last 4 characters of a token, replacing the middle with ellipsis:

```
sk-abc123456789xyz → sk-abc1…9xyz
```

PEM private key blocks preserve the first and last lines, with the middle replaced by `…redacted…`.

Redaction has two modes: `"tools"` mode (default) only redacts sensitive information in tool output; `"off"` mode disables redaction.

## 34.1.3 WebSocket Logging (`src/gateway/ws-log.ts`)

Gateway's WebSocket communication generates substantial logs—every RPC call, every message broadcast, and every connection event needs to be recorded. `ws-log.ts` provides a specialized set of WebSocket log formatting tools.

### Log Formatting

`formatForLog()` safely converts any value to a log-friendly string, limiting length to 240 characters, and automatically redacts sensitive information:

```typescript
export function formatForLog(value: unknown): string {
  // Error objects: extract name + message + code
  if (value instanceof Error) {
    return `${value.name}: ${value.message}${value.code ? ` code=${value.code}` : ""}`;
  }
  // Objects: extract message field
  if (typeof value === "object" && value?.message) { ... }
  // Others: JSON.stringify + redact + truncate
  const str = typeof value === "string" ? value : JSON.stringify(value);
  return redactSensitiveText(str, WS_LOG_REDACT_OPTIONS).slice(0, 240);
}
```

### ID Abbreviation

Frequently appearing UUIDs in WebSocket messages are abbreviated to `first8…last4` format:

```typescript
export function shortId(value: string): string {
  if (UUID_RE.test(value)) return `${value.slice(0, 8)}…${value.slice(-4)}`;
  if (value.length <= 24) return value;
  return `${value.slice(0, 12)}…${value.slice(-4)}`;
}
```

### Log Subsystem

WebSocket logs use the `"gateway/ws"` subsystem identifier, displayed as `[ws]` on the console (the `gateway` prefix is automatically stripped).

***

## Section Summary

1. **tslog Foundation**: OpenClaw uses tslog as the logging framework, running in `hidden` mode (no ANSI output), forwarding JSON logs to files through custom transports
2. **Seven Log Levels**: silent → fatal → error → warn → info → debug → trace, default level info, console elevated to debug in verbose mode
3. **Dual-Track Output**: File track (JSON format, daily rolling, 24h auto-cleanup) and console track (three styles: pretty/compact/json, subsystem color-coded)
4. **Subsystem Logger**: `createSubsystemLogger("discord")` creates prefixed logger instances, supports hierarchical structure and subsystem filtering, console colors assigned via name hashing
5. **Console Capture**: Hijacks global `console.*` methods, simultaneously writes to file log, supports noise suppression, EPIPE fault tolerance, and stderr redirection
6. **Sensitive Information Redaction**: Regex-driven engine automatically identifies API Keys, Tokens, passwords, etc., preserving first and last characters while replacing the middle
7. **WebSocket Logging**: Specialized formatting tools limit output length, abbreviate UUIDs, auto-redact, using `gateway/ws` subsystem identifier
