openclaw-logger
v1.0.0
Published
Structured logging for OpenClaw agents and automation tasks with JSON/CSV export, filtering, and archival
Maintainers
Readme
openclaw-logger v1.0.0
Structured logging for OpenClaw agents and automation tasks
A lightweight, zero-dependency logging library designed specifically for OpenClaw agents, cron tasks, and homelab automation. Store, filter, export, and analyze logs with JSON or CSV formats.
Features
✅ Structured Logging — JSON format for easy parsing and analysis
✅ Multiple Log Levels — debug, info, warn, error with filtering
✅ Rich Metadata — Attach custom metadata and tags to every log
✅ Export Formats — JSON and CSV export for dashboarding and reporting
✅ Log Filtering — Search by level, message pattern, or custom tags
✅ Automatic Archival — Auto-archive logs when they exceed max lines
✅ Statistics — Built-in stats and error rate calculation
✅ CLI Tool — Command-line interface for quick logging ops
✅ Zero Dependencies — Pure Node.js, no external packages
✅ Session Isolation — Per-session logging with automatic segregation
Installation
npm install openclaw-loggerOr globally for CLI access:
npm install -g openclaw-loggerQuick Start
CLI Usage
# Log a message
openclaw-log log info "Task started"
# View recent logs
openclaw-log tail 10
# Get statistics
openclaw-log stats
# Export to CSV
openclaw-log export csv > logs.csv
# Filter logs
openclaw-log filter error "timeout"Programmatic Usage
const OpenClawLogger = require('openclaw-logger');
// Create logger instance
const logger = new OpenClawLogger({
sessionId: 'my-agent',
minLevel: 'debug'
});
// Log messages
logger.info('Task started');
logger.error('Connection failed', { retries: 3 });
// Add tags to all subsequent logs
logger.setTags({
env: 'production',
version: '1.0.0'
});
// View logs
const logs = logger.readLogs({ level: 'error', limit: 20 });
console.log(logs);
// Get statistics
const stats = logger.stats();
console.log(`Total errors: ${stats.byLevel.error}`);
// Export
const json = logger.export('json');
const csv = logger.export('csv');API Reference
Constructor
const logger = new OpenClawLogger({
sessionId: 'my-session', // Default: 'default'
logDir: './logs', // Default: ~/.openclaw/logs
logFile: './custom.jsonl', // Default: sessionId.jsonl
maxLines: 100000, // Auto-archive at this count
archiveDir: './logs/archive', // Where to archive old logs
minLevel: 'debug', // Minimum log level to record
tags: { env: 'prod' } // Initial tags for all logs
});Logging Methods
logger.debug(message, metadata); // Detailed diagnostic info
logger.info(message, metadata); // General information
logger.warn(message, metadata); // Warning conditions
logger.error(message, metadata); // Error conditionsParameters:
message(string) — Log messagemetadata(object, optional) — Additional data to attach
Returns: Logger instance (for chaining)
Example:
logger
.info('Processing file', { file: 'data.json', size: '5MB' })
.addTag('step', 'validation')
.warn('Large file detected', { threshold: '10MB' });Tag Management
logger.setTags({ env: 'prod', version: '2.1' }); // Replace all tags
logger.addTag('region', 'us-east'); // Add single tagReading Logs
const logs = logger.readLogs({
level: 'error', // Filter by level
message: 'timeout', // Filter by message pattern (regex)
since: '2026-02-25', // Filter by date (ISO string)
tag: 'env', // Filter by tag
tagValue: 'production', // Tag value to match
limit: 50 // Max results to return
});Returns: Array of log objects
Example Log Object:
{
timestamp: '2026-02-25T01:45:30.123Z',
session: 'my-agent',
level: 'error',
message: 'Connection failed',
env: 'production',
retries: 3
}Statistics & Summaries
const stats = logger.stats();
// Returns:
// {
// total: 1250,
// byLevel: { debug: 500, info: 400, warn: 200, error: 150 },
// errorRate: '12.00%',
// errors: ['Connection timeout', 'Database unavailable'],
// warnings: ['High memory usage', 'Slow query']
// }
const summary = logger.summary();
// Returns:
// {
// session: 'my-agent',
// logFile: '/home/.openclaw/logs/my-agent.jsonl',
// total: 1250,
// byLevel: {...},
// errorRate: '12.00%'
// }Export
// JSON export (full objects)
const json = logger.export('json');
// Returns JSON array of log objects
// CSV export (tabular format)
const csv = logger.export('csv', {
level: 'error', // Optional: filter params
limit: 100
});
// Returns CSV string with headers
// Save to file
const fs = require('fs');
fs.writeFileSync('logs.csv', logger.export('csv'));Maintenance
logger.clear(); // Delete all logs for this sessionReal-World Examples
Monitoring Agent Tasks
const logger = new OpenClawLogger({ sessionId: 'backup-agent' });
logger.setTags({ agent: 'backup', env: 'production' });
try {
logger.info('Backup started', { size: '500GB' });
// ... backup logic ...
logger.info('Backup completed', { duration: '2h30m', files: 15000 });
} catch (error) {
logger.error('Backup failed', { error: error.message, attempted: 12000 });
}Filtering Critical Errors
const logger = new OpenClawLogger({ sessionId: 'system' });
// ... logging happens ...
// Find all timeout errors from the last hour
const timeouts = logger.readLogs({
level: 'error',
message: 'timeout',
since: new Date(Date.now() - 3600000).toISOString()
});
console.log(`Found ${timeouts.length} timeout errors in last hour`);Exporting for Dashboard
const logger = new OpenClawLogger({ sessionId: 'api-gateway' });
// Export last 24 hours of logs
const oneDayAgo = new Date(Date.now() - 86400000).toISOString();
const logs = logger.readLogs({ since: oneDayAgo });
// Convert to CSV and send to dashboard
const csv = logger.export('csv', { since: oneDayAgo });
fs.writeFileSync('./dashboard-data.csv', csv);Per-Task Logging
function runTask(taskId) {
const logger = new OpenClawLogger({ sessionId: `task-${taskId}` });
logger.setTags({ taskId, startTime: new Date().toISOString() });
logger.info('Task started');
// ... task execution ...
logger.info('Task completed');
return logger.stats();
}Directory Structure
Logs are stored in ~/.openclaw/logs/ by default:
~/.openclaw/logs/
├── my-agent.jsonl # Active logs for session
├── backup-agent.jsonl
├── system.jsonl
└── archive/
├── my-agent-2026-02-25.jsonl
├── my-agent-2026-02-24.jsonl
└── backup-agent-2026-02-25.jsonlEach line in .jsonl files is a complete JSON log object.
Performance Characteristics
- Append Speed: ~10,000 logs/second (single session)
- Read Speed: ~50,000 logs/second (filtering)
- Memory: <5MB typical footprint
- File Size: ~500KB per 10,000 logs
- Auto-Archive: Triggered at 100,000 lines (configurable)
Integration with OpenClaw
In Cron Tasks
const OpenClawLogger = require('openclaw-logger');
const logger = new OpenClawLogger({
sessionId: process.env.OPENCLAW_CRON_ID || 'cron-task'
});
// Your cron task logic
logger.info('Cron task executed');In Agents
const OpenClawLogger = require('openclaw-logger');
const logger = new OpenClawLogger({
sessionId: process.env.OPENCLAW_SESSION || 'agent'
});
logger.setTags({
agent: process.env.AGENT_ID,
model: process.env.AGENT_MODEL
});CLI Commands
openclaw-log log <level> <message> # Write log entry
openclaw-log tail [N] # Show last N logs
openclaw-log stats # Show statistics
openclaw-log summary # Same as stats
openclaw-log export [json|csv] # Export all logs
openclaw-log filter <level> <pattern> # Filter logs
openclaw-log clear # Delete all logs
openclaw-log help # Show helpTesting
Run the included test suite (20 tests):
npm testAll tests pass with zero dependencies.
License
MIT © 2026 botfit
Author
botfit — OpenClaw Community
Email: [email protected]
GitHub: @openclaw
Changelog
v1.0.0 (2026-02-25)
- ✅ Initial release
- ✅ Structured JSON logging
- ✅ JSON and CSV export
- ✅ Log filtering by level, message, date, tags
- ✅ Statistics and health reporting
- ✅ CLI interface
- ✅ Session-based isolation
- ✅ Automatic log archival
- ✅ Zero dependencies
- ✅ 20/20 tests passing
Support
For issues, questions, or contributions:
- 📧 Email: [email protected]
- 🐙 GitHub: https://github.com/openclaw/openclaw-logger
- 📦 npm: https://www.npmjs.com/package/openclaw-logger
Made with ❤️ for OpenClaw automation engineers
