Refactor SSE logging

This commit is contained in:
josedario87
2025-06-11 19:23:34 -06:00
parent e7dea54592
commit ad5bfc788f
2 changed files with 53 additions and 1 deletions

View File

@@ -1,7 +1,8 @@
import express from 'express'; import express from 'express';
import dotenv from 'dotenv'; import dotenv from 'dotenv';
import { registerConversationRoutes } from './routes/conversationActions'; import { registerConversationRoutes } from './routes/conversationActions';
import whatsappActionsRouter from './routes/whatsappActions'; // New import import whatsappActionsRouter from './routes/whatsappActions';
import { registerLogSse } from './sse/logSse';
import { import {
registerWebhookRoutes, registerWebhookRoutes,
clearWebhooks, clearWebhooks,
@@ -39,6 +40,8 @@ if (
const app = express(); const app = express();
app.use(express.json()); app.use(express.json());
registerLogSse(app);
const port = Number(process.env.PORT) || 3001; const port = Number(process.env.PORT) || 3001;
const agentUrl = process.env.LLM_AGENT_URL as string | undefined; const agentUrl = process.env.LLM_AGENT_URL as string | undefined;
const openWaUrl = process.env.OPEN_WA_URL as string | undefined; const openWaUrl = process.env.OPEN_WA_URL as string | undefined;

View File

@@ -0,0 +1,49 @@
import { Express, Response } from 'express';
export function registerLogSse(app: Express) {
const clients: Response[] = [];
app.get('/logs/sse', (req, res) => {
res.set({
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no',
});
res.flushHeaders();
res.write('event: connected\ndata: {}\n\n');
const keepAlive = setInterval(() => {
res.write(':\n\n');
}, 15000);
clients.push(res);
console.log('🟢 SSE log client connected (%d)', clients.length);
req.on('close', () => {
clearInterval(keepAlive);
clients.splice(clients.indexOf(res), 1);
console.log('🔌 SSE log client disconnected (%d)', clients.length);
});
});
const broadcast = (data: string) => {
const payload = `data: ${data}\n\n`;
clients.forEach((c) => c.write(payload));
};
const originalLog = console.log;
const originalError = console.error;
console.log = (...args: any[]) => {
originalLog(...args);
broadcast(args.join(' '));
};
console.error = (...args: any[]) => {
originalError(...args);
broadcast(args.join(' '));
};
}