# Winston Logging Integration

## Overview
Winston logging has been successfully integrated into the QuantCapital Admin application to track API endpoint hits and capture error logs.

## Features Implemented

### 1. Dual Logging Outputs
- **Terminal/Console**: Shows all endpoint hits with colored output
- **Log Files**: Stores error logs in the `/logs` directory with daily rotation

### 2. Log Files Created
- `logs/error-YYYY-MM-DD.log` - Error logs only
- `logs/combined-YYYY-MM-DD.log` - All logs (info, http, warn, error)
- `logs/exceptions-YYYY-MM-DD.log` - Uncaught exceptions
- `logs/rejections-YYYY-MM-DD.log` - Unhandled promise rejections

### 3. Log Retention
- Logs are rotated daily
- 7 days retention period
- Automatic compression of old logs
- Max file size: 20MB per log file

## Files Modified

### Core Configuration
- `config/logger.config.js` - Winston configuration with transports and formats
- `utils/logger.js` - Logger utility with helper functions

### API Integration
- `pages/api/apiclient.js` - Added logging to all HTTP methods (GET, POST, PUT, DELETE)
- `pages/api/media.js` - Added logging to file upload endpoint

### Error Handling
- `pages/components/MenuScreen/utils/errorHandler.js` - Integrated Winston for error logging
- `context/Context.js` - Replaced console.error with Winston logging

## How It Works

### Terminal Output
When running the application, you'll see colored logs in the terminal showing:
- **Cyan**: API requests and responses (endpoint hits)
- **Green**: Informational messages
- **Yellow**: Warnings
- **Red**: Errors

Example:
```
[2025-10-30 19:25:04] http: API Request: GET http://localhost:4800/auth/v1/getAllUsers | Endpoint: GET http://localhost:4800/auth/v1/getAllUsers
[2025-10-30 19:25:04] http: API Response: POST http://localhost:4800/auth/v1/investAmount - 200 | Status: 200 | Duration: 145ms
[2025-10-30 19:25:04] error: Error in API GET Error: Request failed | url: http://localhost:4800/auth/v1/users | statusCode: 500
```

### Log Files
Error logs are stored in JSON format for easy parsing:
```json
{
  "level": "error",
  "message": "Error in API GET Error: Request failed",
  "timestamp": "2025-10-30 19:25:04",
  "context": "API GET Error",
  "url": "http://localhost:4800/auth/v1/users",
  "statusCode": 500,
  "stack": "Error: Request failed\n    at ..."
}
```

## Usage Examples

### In Your Code
```javascript
import { logEndpointHit, logError, logApiResponse, logInfo, logWarning } from '../utils/logger';

// Log when an endpoint is hit
logEndpointHit('POST', '/api/users', { userId: '12345' });

// Log API response
logApiResponse('POST', '/api/users', 200, 145, { userId: '12345' });

// Log errors
try {
  // Some operation
} catch (error) {
  logError(error, 'User Creation Failed', {
    userId: '12345',
    operation: 'createUser'
  });
}

// Log informational messages
logInfo('User successfully created', { userId: '12345' });

// Log warnings
logWarning('API rate limit approaching', { current: 950, limit: 1000 });
```

## Viewing Logs

### View Error Logs
```bash
# View today's error logs
cat logs/error-$(date +%Y-%m-%d).log

# View all error logs
cat logs/error-*.log

# Follow error logs in real-time
tail -f logs/error-*.log
```

### View Combined Logs
```bash
# View today's combined logs
cat logs/combined-$(date +%Y-%m-%d).log

# View specific log level (using jq for JSON parsing)
cat logs/combined-*.log | jq 'select(.level == "error")'
```

### Search Logs
```bash
# Search for specific endpoint
grep "getAllUsers" logs/combined-*.log

# Search for errors with status code 500
cat logs/error-*.log | jq 'select(.statusCode == 500)'

# Count errors by endpoint
cat logs/error-*.log | jq -r '.endpoint' | sort | uniq -c
```

## Environment Configuration

Winston works in both development and production environments:
- **Development**: Full logging to console + files
- **Production**: Reduced console logging, full file logging

## Benefits

1. **Visibility**: See every endpoint hit in the terminal
2. **Debugging**: Full stack traces and context in error logs
3. **Monitoring**: Easy to parse JSON logs for analysis
4. **Performance**: Track API response times (duration)
5. **Audit Trail**: 7-day retention for troubleshooting
6. **Automatic Rotation**: No manual log management needed

## Notes

- Logs directory is git-ignored (logs/*.log)
- Log files are automatically compressed when rotated
- Winston handles both server-side (Node.js) and client-side (browser) logging
- Client-side logs fall back to console with colored output
- No performance impact on production (async logging)

## Troubleshooting

### If logs are not appearing:
1. Check that `/logs` directory exists and is writable
2. Verify Winston packages are installed: `npm list winston`
3. Check for errors in the console during startup

### If log files are too large:
- Adjust `maxSize` in `config/logger.config.js`
- Reduce `maxFiles` retention period
- Adjust log level filtering

### If you need more detailed logs:
- Change console transport level from 'http' to 'debug' in `config/logger.config.js`
- Add more context to logError calls throughout the application

## Next Steps (Optional Enhancements)

1. **Remote Logging**: Send logs to external services (Loggly, Datadog, Splunk)
2. **Log Dashboard**: Create a web interface to view logs
3. **Alerts**: Set up notifications for critical errors
4. **Log Analysis**: Integrate with ELK stack or similar
5. **Performance Metrics**: Add custom metrics tracking

---

For questions or issues, refer to the Winston documentation: https://github.com/winstonjs/winston
