Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | 1x 1x 1x 1x 1x 1x 1x 1x | const fs = require('fs').promises;
const path = require('path');
const chokidar = require('chokidar');
const logger = require('./logger');
class LogCollector {
constructor() {
this.watchers = new Map();
this.logBuffer = [];
this.lastReadPositions = new Map();
}
async startWatching(projectConfigs) {
for (const project of projectConfigs) {
if (!project.enabled) continue;
// Watch custom log paths
for (const logPath of project.custom_log_paths || []) {
await this.watchLogFile(logPath, project.project_name);
}
// Watch common log locations in project directory
await this.watchProjectLogs(project.pwd_path, project.project_name);
}
}
async watchLogFile(logPath, projectName) {
try {
// Check if file exists
await fs.access(logPath);
// Initialize read position
const stats = await fs.stat(logPath);
this.lastReadPositions.set(logPath, stats.size);
// Watch for changes
const watcher = chokidar.watch(logPath, {
persistent: true,
usePolling: true,
interval: 1000
});
watcher.on('change', async () => {
await this.readNewLogContent(logPath, projectName);
});
this.watchers.set(logPath, watcher);
logger.info(`Started watching log file: ${logPath} for project: ${projectName}`);
} catch (error) {
logger.warn(`Cannot watch log file ${logPath}:`, error.message);
}
}
async watchProjectLogs(projectPath, projectName) {
try {
// Common log directories and patterns
const logPatterns = [
path.join(projectPath, 'logs', '*.log'),
path.join(projectPath, 'log', '*.log'),
path.join(projectPath, '*.log'),
path.join(projectPath, 'var', 'log', '*.log')
];
for (const pattern of logPatterns) {
const watcher = chokidar.watch(pattern, {
persistent: true,
usePolling: true,
interval: 1000,
ignoreInitial: false
});
watcher.on('add', async (filePath) => {
logger.info(`New log file detected: ${filePath}`);
await this.initializeLogFile(filePath, projectName);
});
watcher.on('change', async (filePath) => {
await this.readNewLogContent(filePath, projectName);
});
this.watchers.set(pattern, watcher);
}
logger.info(`Started watching project logs in: ${projectPath}`);
} catch (error) {
logger.error(`Error watching project logs in ${projectPath}:`, error);
}
}
async initializeLogFile(filePath, projectName) {
try {
const stats = await fs.stat(filePath);
this.lastReadPositions.set(filePath, stats.size);
logger.info(`Initialized log file: ${filePath} for project: ${projectName}`);
} catch (error) {
logger.error(`Error initializing log file ${filePath}:`, error);
}
}
async readNewLogContent(filePath, projectName) {
try {
const stats = await fs.stat(filePath);
const lastPosition = this.lastReadPositions.get(filePath) || 0;
if (stats.size <= lastPosition) {
// File might have been truncated
this.lastReadPositions.set(filePath, 0);
return;
}
// Read new content
const fileHandle = await fs.open(filePath, 'r');
const buffer = Buffer.alloc(stats.size - lastPosition);
const { bytesRead } = await fileHandle.read(
buffer,
0,
buffer.length,
lastPosition
);
await fileHandle.close();
if (bytesRead > 0) {
const newContent = buffer.slice(0, bytesRead).toString('utf8');
await this.processLogContent(newContent, filePath, projectName);
this.lastReadPositions.set(filePath, stats.size);
}
} catch (error) {
logger.error(`Error reading log file ${filePath}:`, error);
}
}
async processLogContent(content, source, projectName) {
const lines = content.split('\n').filter(line => line.trim());
for (const line of lines) {
const logEntry = this.parseLogLine(line, source, projectName);
if (logEntry) {
this.logBuffer.push(logEntry);
}
}
}
parseLogLine(line, source, projectName) {
try {
// Try to parse as JSON first
const jsonLog = JSON.parse(line);
return {
timestamp: new Date(jsonLog.timestamp || Date.now()),
level: this.normalizeLogLevel(jsonLog.level || 'INFO'),
message: jsonLog.message || line,
source: source,
projectName: projectName,
metadata: jsonLog
};
} catch (jsonError) {
// Fall back to text parsing
return this.parseTextLog(line, source, projectName);
}
}
parseTextLog(line, source, projectName) {
// Simple regex patterns for common log formats
const patterns = [
// ISO timestamp with level
/^(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})?)\s+\[?(\w+)\]?\s*(.+)$/,
// Syslog format
/^(\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2})\s+\w+\s+\w+\[?\d*\]?:\s*(.+)$/,
// Simple timestamp
/^(\d{2}\/\d{2}\/\d{4}\s+\d{2}:\d{2}:\d{2})\s+\[?(\w+)\]?\s*(.+)$/
];
for (const pattern of patterns) {
const match = line.match(pattern);
if (match) {
return {
timestamp: new Date(match[1]),
level: this.normalizeLogLevel(match[2] || 'INFO'),
message: match[3] || match[2] || line,
source: source,
projectName: projectName,
metadata: { rawLine: line }
};
}
}
// If no pattern matches, treat as info log
return {
timestamp: new Date(),
level: 'INFO',
message: line,
source: source,
projectName: projectName,
metadata: { rawLine: line }
};
}
normalizeLogLevel(level) {
const levelMap = {
'TRACE': 'DEBUG',
'DEBUG': 'DEBUG',
'INFO': 'INFO',
'INFORMATION': 'INFO',
'WARN': 'WARN',
'WARNING': 'WARN',
'ERROR': 'ERROR',
'ERR': 'ERROR',
'FATAL': 'FATAL',
'CRITICAL': 'FATAL'
};
return levelMap[level?.toUpperCase()] || 'INFO';
}
getBufferedLogs() {
const logs = [...this.logBuffer];
this.logBuffer = [];
return logs;
}
stopWatching() {
for (const [path, watcher] of this.watchers) {
watcher.close();
logger.info(`Stopped watching: ${path}`);
}
this.watchers.clear();
}
}
module.exports = LogCollector;
|