Repository navigation
feat: created file based logging with aws credentials - #410
Conversation
|
fixing something will update you on this |
|
@tonychang04 pls review |
|
Can you also give screenshot of after you started docker? and go to analytics page? we want to make sure all operations are functional |
|
Okay sure |
|
@tonychang04 here is a video form starting going to analytics page Screen.Recording.2025-10-14.at.12.mp4 |
|
@tonychang04 pls take a look once again and let me know |
|
Hi @HarshSharma0801
The behavior is that there are actually loaded logs + content, which is differnt in your video. |
5a2ef5f to
dca8398
Compare
|
hey @tonychang04 thanks for your inputs , i have made adjustments to the log structure we get locally to match with cloudwatch ones , also i have rebased and made adjustments to the files according to latest changes here is the video Screen.Recording.2025-10-14.at.12.1.mp4 |
|
Looking better!!! i'm wondering can the same method be used for different containers...? We can see when we add the cloudwatch.. we have 4 containers with logs.. but with your method, is it possible to aggregate and show the differet containers' logs? Also if you can help rebase your branch, we recently change analytics -> logs so somethings may be slighly off |
|
hey @tonychang04 as requested , did logs locally for all four containers , approach is simple we have vector container that has vector yaml file based on having aws credentials , if local then reads and formats the logs into a shared volume that is shared by insforge container through which fileprovider access the logs and send back to frontend , here is a video and screenshot , for rebasing i have already rebased with main pls take a look at it .
Screen.Recording.2025-10-14.at.2.mp4 |
|
|
||
| async getLogSources(): Promise<LogSourceSchema[]> { | ||
| if (!this.cwLogGroup || !this.cwClient) { | ||
| throw new AppError( |
| @@ -0,0 +1,81 @@ | |||
| import { CloudWatchProvider } from './cloudwatch.provider.js'; | |||
| import { BaseAnalyticsProvider } from './base.provider.js'; | |||
| import { LogSource, AnalyticsLogRecord, LogSourceStats } from '@/types/logs.js'; | |||
There was a problem hiding this comment.
Cloiudwatch logs should be ready? do we need another cloudwatch-analytics provider?
| } | ||
|
|
||
| // Analytics Provider Interface | ||
| export interface AnalyticsProvider { |
There was a problem hiding this comment.
I think we removed the naming of Analytics and just call it logs
https://github.com/InsForge/InsForge/pull/381/files
|
|
||
| await this.provider.initialize(); | ||
| } | ||
|
|
There was a problem hiding this comment.
we should already have these files in logs/logs.ts ... maybe you rebased it incorrectly?
|
This looks really cool from the demo! we recently done a refractor to remove |
|
cool I will rebase once again and make these minor changes, if I find some issues we can connect surely , can you please list down the changes in files thanks |
|
for sure! happy to hop on a call bout this. This is an important feature! |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
backend/src/core/logs/providers/file.provider.ts (2)
68-124: Consider streaming for large log files.The current implementation reads the entire file into memory before slicing to the limit (line 123). For large production log files (potentially gigabytes), this could cause memory pressure and slow response times.
Consider these optimizations:
- For reverse-chronological queries, read the file from the end using a reverse line reader.
- Track file positions and implement cursor-based pagination.
- Add a maximum file size check and warn if files exceed a threshold.
Example approach using reverse iteration:
private async readLogsFromFileReverse( filePath: string, limit: number, beforeTimestamp?: string ): Promise<LogSchema[]> { const logs: LogSchema[] = []; const beforeMs = beforeTimestamp ? Date.parse(beforeTimestamp) : Date.now(); // Read file in chunks from the end const stat = await fs.stat(filePath); const fileSize = stat.size; const chunkSize = 64 * 1024; // 64KB chunks let position = fileSize; let buffer = ''; while (position > 0 && logs.length < limit) { const readSize = Math.min(chunkSize, position); position -= readSize; const chunk = Buffer.alloc(readSize); const fd = await fs.open(filePath, 'r'); await fd.read(chunk, 0, readSize, position); await fd.close(); buffer = chunk.toString() + buffer; const lines = buffer.split('\n'); buffer = lines[0]; // Keep incomplete first line for next iteration // Process lines from end to start for (let i = lines.length - 1; i >= 1; i--) { // ... parse and filter logic ... if (logs.length >= limit) break; } } return logs.reverse(); // Reverse to maintain chronological order }
148-186: Reduce memory footprint for log search.Loading up to 10,000 logs per source file (line 170) into memory can be expensive, especially when searching across multiple sources. For deployments with high log volumes, this could cause timeouts or OOM errors.
Apply this diff to add an early termination mechanism:
async searchLogs( query: string, sourceName?: string, limit: number = 100, offset: number = 0 ): Promise<{ logs: (LogSchema & { source: string })[]; total: number; }> { const results: (LogSchema & { source: string })[] = []; const searchLower = query.toLowerCase(); const filesToSearch = sourceName ? [{ name: sourceName, filename: this.logFiles[sourceName] }] : Object.entries(this.logFiles).map(([name, filename]) => ({ name, filename })); for (const { name, filename } of filesToSearch) { if (!filename) { continue; } const filePath = path.join(this.logsDir, filename); - const logs = await this.readLogsFromFile(filePath, 10000); + // Only read enough logs to satisfy limit + offset + const maxNeeded = offset + limit; + const logs = await this.readLogsFromFile(filePath, Math.min(10000, maxNeeded * 2)); for (const log of logs) { const messageMatch = log.eventMessage.toLowerCase().includes(searchLower); const metadataMatch = JSON.stringify(log.body).toLowerCase().includes(searchLower); if (messageMatch || metadataMatch) { results.push({ ...log, source: name }); + // Early termination if we have enough results + if (results.length >= maxNeeded + 1000) { + break; + } } } } return { logs: results.slice(offset, offset + limit), total: results.length, }; }Additionally, consider implementing streaming search for large-scale deployments.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
backend/src/core/logs/providers/file.provider.ts(1 hunks)backend/src/core/logs/writer.ts(1 hunks)docker-compose.yml(5 hunks)docker-init/logs/vector.yml(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- backend/src/core/logs/writer.ts
🧰 Additional context used
🧬 Code graph analysis (1)
backend/src/core/logs/providers/file.provider.ts (1)
shared-schemas/src/logs.schema.ts (3)
LogSourceSchema(38-38)LogSchema(39-39)LogStatsSchema(40-40)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: E2E Tests
🔇 Additional comments (7)
docker-init/logs/vector.yml (2)
166-189: LGTM! File sink paths are consistent.The JSONL file paths match the structure expected by the FileProvider and align with the shared volume configuration in docker-compose.yml.
191-227: Verify Vector degrades gracefully without AWS credentials
Confirm that starting Vector with the CloudWatch sinks enabled—but without any AWS credentials—does not cause startup failures or excessive error logs.docker-compose.yml (2)
100-101: LGTM! Centralized log directory configuration is consistent.The
LOGS_DIRenvironment variable and volume mount align with the Vector configuration (/insforge-logs) and the FileProvider implementation. This provides a clear contract for log storage location.Also applies to: 112-112
162-181: Verify Vector startup behavior without AWS credentials.The Vector service now starts with
restart: unless-stoppedand a simplified command, removing previous credential-gating logic. This change improves the developer experience, but ensure Vector doesn't repeatedly fail and restart when CloudWatch sinks can't authenticate.Test the following scenario:
- Remove AWS credentials from
.env- Run
docker compose up vector- Monitor logs with
docker logs -f insforge-vectorfor ~30 seconds- Confirm: no repeated authentication errors, file sinks work, service stays healthy
Expected outcome: Vector should log a warning about missing AWS credentials but continue operating with file sinks only.
backend/src/core/logs/providers/file.provider.ts (3)
27-42: TypeScript error resolved.The previous review flagged
LogSourceas undefined. The code now correctly usesLogSourceSchema[]from the imported schema, resolving the TypeScript compilation error.
17-25: LGTM! Directory initialization is robust.The initialization properly resolves the log directory from the environment, creates it recursively, and logs the path for debugging. The try-catch handles the case where the directory already exists.
44-66: LGTM! Log retrieval by source is well-structured.The method correctly maps source names to filenames and delegates to the file reader with appropriate defaults.
20090b5 to
94e7597
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
backend/src/core/logs/providers/file.provider.ts (2)
62-118: Refactor to avoid loading entire file into memory.The current implementation reads all matching lines into the
logsarray (line 104), then slices to the lastlimitentries (line 117). For large log files (e.g., 100k+ lines), this approach:
- Consumes excessive memory.
- Delays response time (reads entire file even if only 100 recent logs are needed).
Consider a reverse file reading approach to fetch only the most recent logs:
- Open the file in reverse (using a library like
reverse-line-readeror a custom tail-like implementation).- Parse lines backward until
limitis reached or timestamp condition fails.- Stop early without reading the entire file.
Example skeleton (requires a reverse-read utility):
private async readLogsFromFile( filePath: string, limit: number, beforeTimestamp?: string ): Promise<LogSchema[]> { const logs: LogSchema[] = []; const beforeMs = beforeTimestamp ? Date.parse(beforeTimestamp) : Date.now(); // Pseudo-code: reverse iteration for await (const line of reverseReadLines(filePath)) { if (logs.length >= limit) break; const log = JSON.parse(line); if (!log.appname) continue; const logTime = new Date(log.timestamp).getTime(); if (logTime >= beforeMs) continue; // ... augment and push log logs.push(transformedLog); } return logs.reverse(); // Restore chronological order }Alternatively, for simpler cases, use Node.js
fs.readwithpositionoffsets to seek near the end of the file and scan backwards.
142-180: Optimize memory usage for search operations.The method reads up to 10,000 logs per file into memory (line 164), builds the entire
resultsarray (line 171), then slices for pagination (line 177). For multi-file searches across large datasets, this approach:
- Consumes significant memory (e.g., 4 files × 10k logs = 40k objects in memory).
- Delays response even when
limitis small (e.g.,limit=10still processes 40k logs).Consider streaming pagination:
- Track a running offset/limit across files.
- Stop reading once
offset + limitresults are collected.- Avoid building the full results array.
Example skeleton:
async searchLogs( query: string, sourceName?: string, limit: number = 100, offset: number = 0 ): Promise<{ logs: (LogSchema & { source: string })[]; total: number }> { const results: (LogSchema & { source: string })[] = []; const searchLower = query.toLowerCase(); let skipped = 0; let totalMatches = 0; const filesToSearch = sourceName ? [{ name: sourceName, filename: this.logFiles[sourceName] }] : Object.entries(this.logFiles).map(([name, filename]) => ({ name, filename })); for (const { name, filename } of filesToSearch) { if (!filename || results.length >= limit) break; const filePath = path.join(this.logsDir, filename); const logs = await this.readLogsFromFile(filePath, 10000); for (const log of logs) { const matches = log.eventMessage.toLowerCase().includes(searchLower) || JSON.stringify(log.body).toLowerCase().includes(searchLower); if (matches) { totalMatches++; if (skipped < offset) { skipped++; } else if (results.length < limit) { results.push({ ...log, source: name }); } } } } return { logs: results, total: totalMatches }; }Note: This still reads 10k logs per file. For true efficiency, combine with the reverse-read refactor suggested for
readLogsFromFile.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
backend/src/core/logs/providers/file.provider.ts(1 hunks)docker-compose.yml(5 hunks)docker-init/logs/vector.yml(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- docker-init/logs/vector.yml
- docker-compose.yml
🧰 Additional context used
🧬 Code graph analysis (1)
backend/src/core/logs/providers/file.provider.ts (1)
shared-schemas/src/logs.schema.ts (3)
LogSourceSchema(38-38)LogSchema(39-39)LogStatsSchema(40-40)
|
hey @tonychang04 thanks for pointing out changes I have fixed them all of them ,
here is a demo and fixes Screen.Recording.2025-10-15.at.1.mp4 |
|
Amazing work! Adding @Fermionic-Lyu as a 2nd pair of eyes here. Changes now LGTM. We can further test it on our side. And publish to prod! It's great having a solution without AWS cred while trying it's best to mimick the actually log format! |
|
Thanks for the amazing work! Also we might want a cleaning/recyling routine for the local log system. But I think that is out of the scope for this issue. LGTM overall |
|
@Fermionic-Lyu @tonychang04 thanks for reviewing , let me know if anything is needed ! |
|
FileProvider -> LocalFileProvider |
|
@tonychang04 done! |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
backend/src/core/logs/logs.ts (1)
20-33: Clean implementation of provider selection.The conditional logic correctly switches between CloudWatch and file-based logging based on credential availability. The logging provides helpful visibility into which provider is active.
Consider strengthening the credential validation to catch edge cases where credentials might be set to empty strings:
async initialize(): Promise<void> { - // Use CloudWatch if AWS credentials are available, otherwise use file-based logging - const hasAwsCredentials = process.env.AWS_ACCESS_KEY_ID && process.env.AWS_SECRET_ACCESS_KEY; + // Use CloudWatch if AWS credentials are available, otherwise use file-based logging + const hasAwsCredentials = + process.env.AWS_ACCESS_KEY_ID?.trim() && process.env.AWS_SECRET_ACCESS_KEY?.trim();This ensures that credentials must be non-empty strings rather than just truthy values.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
backend/src/core/logs/logs.ts(2 hunks)backend/src/core/logs/providers/file.provider.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- backend/src/core/logs/providers/file.provider.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions
Files:
backend/src/core/logs/logs.ts
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/core/logs/logs.ts
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/logs/logs.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
backend/src/core/logs/logs.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/core/logs/logs.ts
🧬 Code graph analysis (1)
backend/src/core/logs/logs.ts (2)
backend/src/core/logs/providers/cloudwatch.provider.ts (1)
CloudWatchProvider(16-533)backend/src/core/logs/providers/file.provider.ts (1)
LocalFileProvider(8-185)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: E2E Tests
- GitHub Check: CI Pre-merge Check







Summary
solves #366
🎯 Add File-Based Analytics Provider with Auto-Detection
🧩 Summary
Implements a file-based analytics provider as a fallback when AWS CloudWatch credentials are not available, enabling local development and deployment without AWS dependencies.
🔧 Changes
🧠 Core Implementation
Provider Pattern:
Introduced
BaseAnalyticsProviderabstract class defining a common analytics interface.File Provider:
Added new
FileProviderimplementation using Node.js built-ins only:fs.promises,fs.createReadStream,readline, andpathlogs/insforge.logs.jsonllogs/function.logs.jsonlAuto-Detection:
AnalyticsManagerautomatically selects the provider based on AWS credentials presence.Log Writer:
Singleton service integrated into HTTP middleware for asynchronous log writing.
🚀 Benefits
✅ Zero external dependencies (Node.js built-ins only)
✅ Seamless local development without AWS setup
✅ Automatic provider selection based on environment
✅ Consistent analytics interface across providers
✅ Efficient JSONL format for file-based logs
🧪 Testing Guide
🔹 Test FileProvider (Default - No AWS)
How did you test this change?
Screen.Recording.2025-10-13.at.11.1.mp4
Summary by CodeRabbit
New Features
Chores