Skip to content

Commit 20c9e59

Browse files
Saúl Gómez Jiménezclaude
authored andcommitted
feat: migrate logging system from custom transports to Winston
## Summary Migrated Levante's custom logging system (420 lines) to Winston logger while maintaining 100% backward compatibility and zero overhead for disabled categories. ## Key Changes ### New Files - `src/main/services/logging/winstonConfig.ts` - Winston transport configuration - `src/main/services/logging/timezoneFormat.ts` - Timezone support (extracted from transports.ts) - `docs/testing/winston-migration-testing.md` - Comprehensive testing guide - `scripts/test-winston-logging.ts` - Automated testing script ### Modified Files - `src/main/services/logging/logger.ts` - Replaced custom transports with Winston logger - `src/main/services/logging/config.ts` - Added production/development defaults - `src/main/services/logging/index.ts` - Updated exports - `package.json` - Added winston-daily-rotate-file dependency ### Removed Files - `src/main/services/logging/transports.ts` - Replaced by Winston transports (420 lines removed) ## Features ### Production vs Development **Development** (NODE_ENV=development): - Console output with colors - Debug level logging - Verbose categories enabled (ai-sdk, mcp, database, oauth) - Single file: levante-YYYY-MM-DD-HHmmss.log - Rotation: 10MB, 3 files, 7 days **Production** (NODE_ENV=production): - No console output (file only) - Warn level logging - Verbose categories disabled - Two files: all logs + error-only log - Rotation: 50MB, 10 files, 30 days - Gzip compression enabled ### Preserved Features ✅ Zero overhead for disabled categories ✅ 9 categories (ai-sdk, mcp, database, ipc, preferences, models, core, analytics, oauth) ✅ Environment variable configuration ✅ Timezone support ✅ IPC bridge (renderer → main) ✅ Same public API (no breaking changes) ### New Capabilities ✨ Structured JSON logs (production) ✨ Separate error log file (production) ✨ Battle-tested Winston transports ✨ Automatic gzip compression ✨ Winston audit files for rotation tracking ✨ Foundation for future log viewer UI ## Code Impact - Lines added: ~350 - Lines removed: ~420 - Net reduction: ~70 lines - Breaking changes: 0 ## Documentation - Updated `docs/LOGGING.md` with "Arquitectura Winston" section - Updated `CLAUDE.md` logging section - Added comprehensive testing guide ## Testing - ✅ Typecheck passes - ✅ Zero overhead verified - ✅ Backward compatible API - Manual testing required per testing guide Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
1 parent 27d4b28 commit 20c9e59

File tree

12 files changed

+944
-654
lines changed

12 files changed

+944
-654
lines changed

CLAUDE.md

Lines changed: 11 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -285,50 +285,20 @@ Environment variables loaded from:
285285

286286
## Logging System
287287

288-
Levante uses a centralized logging system for better development experience and debugging:
288+
Levante utiliza **Winston** para logging centralizado con sistema de categorías:
289289

290-
### Usage
290+
- **Categorías**: ai-sdk, mcp, database, ipc, preferences, models, core, analytics, oauth
291+
- **Niveles**: debug, info, warn, error
292+
- **Producción**: Logs JSON estructurados con archivo de errores separado
293+
- **Desarrollo**: Salida coloreada legible en consola
294+
- **Zero Overhead**: Categorías deshabilitadas no ejecutan código de log
295+
- **Rotación**: Automática con winston-daily-rotate-file
291296

292-
```typescript
293-
// Main Process
294-
import { getLogger } from './services/logging';
295-
const logger = getLogger();
296-
297-
// Renderer Process
298-
import { logger } from '@/services/logger';
299-
300-
// Usage examples
301-
logger.aiSdk.debug('Model provider loaded', { provider: 'openai' });
302-
logger.mcp.info('Server started', { serverId: 'filesystem' });
303-
logger.database.error('Migration failed', { error: error.message });
304-
logger.core.info('Application initialized');
305-
```
306-
307-
### Categories
308-
309-
- **ai-sdk**: AI service operations, model interactions, streaming
310-
- **mcp**: MCP server management, tool execution, health monitoring
311-
- **database**: Database operations and migrations
312-
- **ipc**: Inter-process communication
313-
- **preferences**: Settings and configuration management
314-
- **core**: General application lifecycle and errors
315-
316-
### Configuration
317-
318-
Control logging via `.env.local`:
319-
320-
```bash
321-
DEBUG_ENABLED=true
322-
DEBUG_AI_SDK=true
323-
DEBUG_MCP=true
324-
DEBUG_DATABASE=false
325-
DEBUG_IPC=false
326-
DEBUG_PREFERENCES=false
327-
DEBUG_CORE=true
328-
LOG_LEVEL=debug
329-
```
297+
**Configuración por Entorno**:
298+
- `NODE_ENV=development`: Verbose, consola, rotación pequeña
299+
- `NODE_ENV=production`: Minimal, solo archivo, rotación grande
330300

331-
See [docs/LOGGING.md](docs/LOGGING.md) for complete documentation.
301+
Ver [docs/LOGGING.md](docs/LOGGING.md) para documentación completa.
332302
- No utilices pnpm dev
333303

334304
## Developer Documentation

docs/LOGGING.md

Lines changed: 131 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -110,21 +110,147 @@ Always include relevant context for better debugging:
110110
111111
```typescript
112112
// Good
113-
logger.aiSdk.debug('Model provider loaded', {
114-
provider: 'openai',
115-
models: 15,
116-
loadTime: '45ms'
113+
logger.aiSdk.debug('Model provider loaded', {
114+
provider: 'openai',
115+
models: 15,
116+
loadTime: '45ms'
117117
});
118118

119119
// Better
120-
logger.mcp.error('Server connection failed', {
120+
logger.mcp.error('Server connection failed', {
121121
serverId: 'filesystem',
122122
error: error.message,
123123
attempt: 3,
124124
timestamp: Date.now()
125125
});
126126
```
127127
128+
## Arquitectura Winston
129+
130+
Levante usa Winston como sistema de logging con las siguientes características:
131+
132+
### Producción vs Desarrollo
133+
134+
El comportamiento del logger cambia según `NODE_ENV`:
135+
136+
**Desarrollo** (`NODE_ENV=development` o no configurado):
137+
- Salida a consola con colores
138+
- Log level: `debug` (muy verboso)
139+
- Categorías verbose habilitadas por defecto: ai-sdk, mcp, database, oauth
140+
- Archivo único: `levante-YYYY-MM-DD-HHmmss.log` (datePattern configurable)
141+
- Rotación: 10MB, 3 archivos, 7 días
142+
143+
**Producción** (`NODE_ENV=production`):
144+
- Sin salida a consola (solo archivo)
145+
- Log level: `warn` (solo warnings y errores)
146+
- Categorías verbose deshabilitadas
147+
- Dos archivos:
148+
- Todos: `levante-YYYY-MM-DD-HHmmss.log`
149+
- Errores: `levante-error-YYYY-MM-DD-HHmmss.log`
150+
- Rotación: 50MB, 10 archivos, 30 días (errores: 90 días)
151+
- Compresión gzip habilitada por defecto
152+
153+
### Archivos de Log
154+
155+
**Ubicación**: `~/levante/`
156+
157+
**Desarrollo**:
158+
```
159+
~/levante/
160+
├── levante-2025-01-28-143025.log # Con datePattern YYYY-MM-DD-HHmmss
161+
├── levante-2025-01-28-120000.log # Rotado anteriormente
162+
└── .winston-audit.json # Tracking de Winston
163+
```
164+
165+
**Producción**:
166+
```
167+
~/levante/
168+
├── levante-2025-01-28-143025.log # Todos los logs
169+
├── levante-error-2025-01-28-143025.log # Solo errores
170+
├── levante-2025-01-27-120000.log.gz # Comprimidos (del día anterior)
171+
├── .winston-audit.json
172+
└── .winston-error-audit.json
173+
```
174+
175+
### Sistema de Rotación
176+
177+
Winston's `winston-daily-rotate-file` maneja:
178+
- **Rotación temporal**: Según datePattern configurado (soporta precisión de segundos con moment.js)
179+
- **Límite de tamaño**: Máximo por archivo antes de comprimir
180+
- **Compresión automática**: Gzip en producción
181+
- **Limpieza por edad**: Elimina logs antiguos según maxAge
182+
- **Tracking**: `.winston-audit.json` para gestión de archivos
183+
184+
### Formato de Logs
185+
186+
**Desarrollo** (legible, con colores):
187+
```
188+
[2025-01-28 14:30:25] [AI-SDK] [DEBUG] Model provider loaded
189+
{
190+
"provider": "openai",
191+
"models": 15
192+
}
193+
```
194+
195+
**Producción** (JSON estructurado):
196+
```json
197+
{
198+
"timestamp": "2025-01-28T14:30:25.123Z",
199+
"level": "error",
200+
"category": "ai-sdk",
201+
"message": "Model provider failed",
202+
"provider": "openai",
203+
"error": "API key invalid"
204+
}
205+
```
206+
207+
### Winston Transports
208+
209+
Levante usa los siguientes transports de Winston:
210+
211+
1. **Console Transport** (solo desarrollo):
212+
- Formato legible con colores ANSI
213+
- Errores a stderr, resto a stdout
214+
215+
2. **DailyRotateFile Transport** (siempre):
216+
- Todos los logs (nivel configurado)
217+
- Rotación automática
218+
219+
3. **DailyRotateFile Transport** (solo producción):
220+
- Solo errores (level: error)
221+
- Retención más larga (3x maxAge)
222+
223+
### Variables de Entorno
224+
225+
Las variables de entorno pueden override los defaults de producción/desarrollo:
226+
227+
```bash
228+
# Forzar level específico (override defaults)
229+
LOG_LEVEL=debug
230+
231+
# Forzar console en producción
232+
DEBUG_ENABLED=true
233+
234+
# Rotación personalizada
235+
LOG_MAX_SIZE=20971520 # 20MB
236+
LOG_MAX_FILES=5
237+
LOG_MAX_AGE=14 # 14 días
238+
LOG_COMPRESS=true
239+
```
240+
241+
### Migración desde Sistema Custom
242+
243+
El sistema Winston mantiene compatibilidad 100% con el API anterior:
244+
- Mismo API de logger: `logger.aiSdk.debug(...)`
245+
- Mismas variables de entorno
246+
- Mismo formato de LogRotationConfig
247+
- Mismo comportamiento de timezone
248+
249+
**Cambios internos** (no afectan uso):
250+
- Transports custom reemplazados por winston transports
251+
- Rotación manejada por winston-daily-rotate-file (usa moment.js, soporta todos los formatos de fecha incluyendo segundos)
252+
- Mismo date pattern que el sistema custom (`YYYY-MM-DD-HHmmss`)
253+
128254
## Log Format
129255
130256
Logs are formatted with timestamps, colored categories, and structured context:

0 commit comments

Comments
 (0)