Skip to content

feat: created file based logging with aws credentials - #410

Merged
tonychang04 merged 19 commits into
InsForge:mainfrom
HarshSharma0801:harsh/feat/366/logs-source
Oct 15, 2025
Merged

tonychang04 merged 19 commits into
InsForge:mainfrom
HarshSharma0801:harsh/feat/366/logs-source

Conversation

@HarshSharma0801

@HarshSharma0801 HarshSharma0801 commented Oct 13, 2025 •

Copy link
Copy Markdown
Contributor

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 BaseAnalyticsProvider abstract class defining a common analytics interface.

  • File Provider:
    Added new FileProvider implementation using Node.js built-ins only:

    • Stores logs in JSONL (JSON Lines) format
    • Uses fs.promises, fs.createReadStream, readline, and path
    • Log files:
      • logs/insforge.logs.jsonl
      • logs/function.logs.jsonl
      • etc.
  • Auto-Detection:
    AnalyticsManager automatically 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)

# 1. Ensure .env has no AWS credentials
cp .env.example .env
# (Leave AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY commented out)

# 2. Start with Docker
docker compose up

# 3. Verify FileProvider is active (check logs)
# Should see: "Using FileProvider for analytics"

# 4. Generate some logs by using the API
# Check logs directory for JSONL files

How did you test this change?

Screen.Recording.2025-10-13.at.11.1.mp4

Summary by CodeRabbit

  • New Features

    • Added automatic local file-based logging when cloud credentials aren’t configured.
    • Introduced configurable log directory via environment variable (LOGS_DIR).
    • Application now writes structured JSONL logs to both console and file.
    • Centralized shared logs volume for services, enabling unified log access.
  • Chores

    • Updated logging pipeline configuration to output JSONL files and optionally forward to cloud logging.
    • Simplified service startup and healthcheck settings for the log collector.
    • Provided example environment updates documenting file-based logging behavior and defaults.

@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

fixing something will update you on this

@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

@tonychang04 pls review

@tonychang04

Copy link
Copy Markdown
Member

Can you also give screenshot of after you started docker? and go to analytics page? we want to make sure all operations are functional

@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

Okay sure

@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

@tonychang04 here is a video form starting going to analytics page

Screen.Recording.2025-10-14.at.12.mp4

@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

@tonychang04 pls take a look once again and let me know

@tonychang04

Copy link
Copy Markdown
Member

Hi @HarshSharma0801
Thanks for tacking this this issue, when you enable aws credentials you see the logs are actually among different containers. We use vector container to define the log source.

Screenshot 2025-10-13 at 16 26 16 Screenshot 2025-10-13 at 16 26 23

The behavior is that there are actually loaded logs + content, which is differnt in your video.

@HarshSharma0801
HarshSharma0801 force-pushed the harsh/feat/366/logs-source branch from 5a2ef5f to dca8398 Compare October 14, 2025 07:08
@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

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
pls let me know

Screen.Recording.2025-10-14.at.12.1.mp4

@tonychang04

tonychang04 commented Oct 14, 2025 •

Copy link
Copy Markdown
Member

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

@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

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 .

Screenshot 2025-10-14 at 2 13 07 PM
Screen.Recording.2025-10-14.at.2.mp4


async getLogSources(): Promise<LogSourceSchema[]> {
if (!this.cwLogGroup || !this.cwClient) {
throw new AppError(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why this change?

@@ -0,0 +1,81 @@
import { CloudWatchProvider } from './cloudwatch.provider.js';
import { BaseAnalyticsProvider } from './base.provider.js';
import { LogSource, AnalyticsLogRecord, LogSourceStats } from '@/types/logs.js';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cloiudwatch logs should be ready? do we need another cloudwatch-analytics provider?

}

// Analytics Provider Interface
export interface AnalyticsProvider {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread backend/src/core/logs/analytics.ts Outdated

await this.provider.initialize();
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should already have these files in logs/logs.ts ... maybe you rebased it incorrectly?

@tonychang04

Copy link
Copy Markdown
Member

This looks really cool from the demo! we recently done a refractor to remove analytics section or endpoints and test. can you do the correspiodnig chagnes..? i saw the analytics code popoping up in different places

@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

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

@tonychang04

tonychang04 commented Oct 14, 2025 •

Copy link
Copy Markdown
Member

for sure! happy to hop on a call bout this. This is an important feature!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. For reverse-chronological queries, read the file from the end using a reverse line reader.
  2. Track file positions and implement cursor-based pagination.
  3. 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

📥 Commits

Reviewing files that changed from the base of the PR and between daec2da and 94e7597.

📒 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_DIR environment 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-stopped and 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:

  1. Remove AWS credentials from .env
  2. Run docker compose up vector
  3. Monitor logs with docker logs -f insforge-vector for ~30 seconds
  4. 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 LogSource as undefined. The code now correctly uses LogSourceSchema[] 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.

@HarshSharma0801
HarshSharma0801 force-pushed the harsh/feat/366/logs-source branch from 20090b5 to 94e7597 Compare October 15, 2025 05:16
@tonychang04

Copy link
Copy Markdown
Member

Honestly amazing work! I'm going to add my buddies to review soon as well

When testing out differences between cloudwatch and local logs. This is what i;'m seeing:

Screenshot 2025-10-14 at 23 16 52 When using cloudwatch credentials we actually have postgrest and postgres logs. One is for the rest apis and one is actually the database. and on local i didn't see postgres

Also when i tried to cause an error. by creating 2 buckets with same name

cloudwatch:
Screenshot 2025-10-14 at 23 20 48

local
Screenshot 2025-10-14 at 23 21 43

The log seems to be different. and than the cloud watch logs?

nits:
Screenshot 2025-10-14 at 23 15 31
empty.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 logs array (line 104), then slices to the last limit entries (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:

  1. Open the file in reverse (using a library like reverse-line-reader or a custom tail-like implementation).
  2. Parse lines backward until limit is reached or timestamp condition fails.
  3. 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.read with position offsets 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 results array (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 limit is small (e.g., limit=10 still processes 40k logs).

Consider streaming pagination:

  1. Track a running offset/limit across files.
  2. Stop reading once offset + limit results are collected.
  3. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 45f3393 and 9f225f5.

📒 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)

@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

hey @tonychang04 thanks for pointing out changes I have fixed them all of them ,

  1. For postgres logs , the code was already there but it was showing on frontend because till then 0 logs were generated in that container, now I have removed that condition

  2. For Error showing there is high mismatch in structuring in how we receive in file system and cloudwatch, but I made adjustments and fixed them

here is a demo and fixes

Screen.Recording.2025-10-15.at.1.mp4

Comment thread docker-compose.yml Resolved
Comment thread backend/src/core/logs/writer.ts Resolved
@tonychang04

Copy link
Copy Markdown
Member

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!

@Fermionic-Lyu

Copy link
Copy Markdown
Member

Thanks for the amazing work!
I just have a nit comment here: maybe FileProvider -> LocalFileProvider for better semantic?

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

@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

@Fermionic-Lyu @tonychang04 thanks for reviewing , let me know if anything is needed !

@tonychang04

Copy link
Copy Markdown
Member

FileProvider -> LocalFileProvider
Just help with the rename, changes makes sense. We can internally test this thoroughly once this is merged!

@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

@tonychang04 done!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9f225f5 and 3afc847.

📒 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Lightweight Self-Hosted Logs Source (No AWS Credentials Required)

3 participants