cube-ms
Version:
Production-ready microservice framework with health monitoring, validation, error handling, and Docker Swarm support
371 lines (286 loc) • 8.6 kB
Markdown
# 📝 CCN Logging Integration
Cube-MS framework includes built-in integration with CCN Logging system untuk centralized logging di lingkungan enterprise.
## 🚀 Quick Setup
### 1. Setup CCN Registry Access
Framework membutuhkan akses ke CCN registry untuk `ccn-logging` dependency.
#### ⚠️ **Token Management Required**
CCN registry menggunakan authentication token yang dapat **expired**. Untuk menghindari masalah expired token:
**🚀 Automatic Setup (Recommended):**
```bash
# Setelah cube-ms create atau clone project
npm run setup-npmrc
```
**🛠️ Manual Setup:**
```bash
# 1. Copy template
cp .npmrc.template .npmrc
# 2. Get your token from CCN DevOps Portal:
# → Go to: http://devops.ccn/
# → Navigate to: CCN Platform Collection → _packaging → CCN.Platform
# → Click "Connect to Feed" → Select "npm"
# → Copy the _password value
# 3. Replace YOUR_TOKEN_HERE in .npmrc with your actual token
```
#### 🔒 **Security Notes**
- `.npmrc` file is **automatically ignored** by git
- **Never commit** `.npmrc` to version control
- Update token **before expiration**
### 2. Environment Configuration
Tambahkan konfigurasi CCN Logging di `.env` file:
```bash
# CCN Logging Configuration
CCN_LOGGING_ENABLED=true
CCN_PRODUCT=MyCubeMSApp
CCN_SERVER_ID=server-001
CCN_APP_ID=my-service
CCN_LOGGING_ENDPOINT=http://logging-service:8080/api/logs
# Log Levels
CCN_LOG_LEVEL_STARTUP=Level2
CCN_LOG_LEVEL_ERROR=Level1
CCN_LOG_LEVEL_SUCCESS=Level3
CCN_LOG_LEVEL_REQUEST=Level4
# Optional: Request/Response logging
CCN_LOG_REQUEST_BODY=false
CCN_LOG_RESPONSE_BODY=false
CCN_LOG_HEADERS=false
```
### 3. Automatic Integration
CCN Logging akan otomatis terintegrasi saat service dimulai:
```javascript
import { CreateService } from 'cube-ms';
const service = CreateService({
port: 3000,
appName: 'MyApp',
serviceName: 'MyService',
// CCN Logging akan otomatis diinisialisasi
});
```
## 📊 Automatic Logging Features
### 1. **Startup Logging** ✅
- Otomatis log saat service dimulai
- Informasi service configuration
- Status initialization
```javascript
// Otomatis dijalankan saat service start
registerCentralLogging();
```
### 2. **Error Logging** ✅
- Semua error otomatis logged ke CCN
- Comprehensive error context
- Sanitized sensitive data
```javascript
// Otomatis di error handler
app.use(globalErrorHandler(logger));
```
### 3. **Success Response Logging** ✅
- HTTP 2xx responses logged
- Request/response details
- Performance metrics (response time)
### 4. **Request Logging** ✅
- Incoming request details
- Sanitized headers dan body
- IP tracking dan User-Agent
## 🛠️ Manual Logging
Anda juga bisa menggunakan CCN logging secara manual:
```javascript
import { logSuccess, logError, logRequest } from 'cube-ms';
// Log successful operations
logSuccess('user_registration', 'User registered successfully', {
userId: '12345',
email: 'user@example.com'
});
// Log errors
logError('database_connection', 'Failed to connect to database', error, {
connectionString: 'mongodb://...',
retryAttempt: 3
});
// Log custom requests
logRequest('external_api_call', 'Called payment service', {
endpoint: '/api/payment',
amount: 100.00,
currency: 'USD'
});
```
## 🔧 Advanced Configuration
### Custom Logger Creation
```javascript
import { createCCNLogger } from 'cube-ms';
const paymentLogger = createCCNLogger('PaymentService');
paymentLogger.info(
'payment_processed',
'Payment successfully processed',
'transaction',
JSON.stringify({ transactionId: 'tx_123', amount: 100 }),
'Level2'
);
```
### Environment-specific Settings
```javascript
// Development
CCN_LOGGING_ENABLED=false # Disable di development
// Staging
CCN_LOGGING_ENABLED=true
CCN_LOG_REQUEST_BODY=true # Enable request body logging
// Production
CCN_LOGGING_ENABLED=true
CCN_LOG_REQUEST_BODY=false # Disable untuk performance
CCN_LOG_HEADERS=false # Disable untuk security
```
## 📋 Log Levels
CCN Logging menggunakan level system:
| Level | Usage | Description |
|-------|-------|-------------|
| **Level1** | Critical Errors | System failures, database down, critical bugs |
| **Level2** | High Priority | Startup, shutdown, important operations |
| **Level3** | Medium Priority | Success operations, business logic |
| **Level4** | Low Priority | Debug info, detailed request logs |
## 🔒 Security Features
### Automatic Data Sanitization
Framework otomatis sanitize sensitive data:
```javascript
// Headers yang di-sanitize
const sensitiveHeaders = [
'authorization', 'cookie', 'x-api-key',
'x-auth-token', 'proxy-authorization'
];
// Body fields yang di-sanitize
const sensitiveFields = [
'password', 'token', 'secret', 'key',
'auth', 'credential', 'pin', 'ssn'
];
```
### Production Safety
```javascript
// Otomatis disable detailed logging di production
if (process.env.NODE_ENV === 'production') {
// Request/response body logging disabled
// Stack traces sanitized
// Sensitive headers redacted
}
```
## 📈 Performance Impact
### Minimal Performance Impact
- Async logging operations
- Request/response logging optional
- Smart sanitization
- Connection pooling
### Optimization Tips
```bash
# Production settings untuk optimal performance
CCN_LOG_REQUEST_BODY=false
CCN_LOG_RESPONSE_BODY=false
CCN_LOG_HEADERS=false
CCN_LOG_LEVEL_REQUEST=Level4 # Set ke Level4 untuk minimal request logs
```
## 🚫 Fallback Behavior
Jika CCN Logging tidak tersedia:
1. **Graceful Degradation**: Service tetap berjalan normal
2. **Console Fallback**: Log ke console sebagai backup
3. **No Service Interruption**: Tidak mempengaruhi aplikasi utama
4. **Error Reporting**: Warning message untuk monitoring
```javascript
// Otomatis fallback ke console logging
if (!ccnLoggingAvailable) {
console.log('CCN Logging not available, using console fallback');
}
```
## 🔍 Monitoring & Health Check
CCN Logging status bisa dicek via health endpoint:
```bash
GET /health
{
"status": "healthy",
"ccnLogging": {
"available": true,
"configured": true,
"endpoint": "http://logging-service:8080/api/logs"
}
}
```
## 📝 Log Format Example
```json
{
"timestamp": "2025-08-12T10:30:00.000Z",
"level": "Level2",
"product": "MyCubeMSApp",
"serverID": "server-001",
"appID": "my-service",
"action": "request_completed",
"message": "GET /api/users completed successfully",
"category": "success",
"details": {
"method": "GET",
"url": "/api/users",
"statusCode": 200,
"duration": "45ms",
"ip": "192.168.1.100",
"userAgent": "Mozilla/5.0...",
"requestId": "req_12345"
}
}
```
## 🆘 Troubleshooting
### Common Issues
1. **"Cannot resolve ccn-logging" / Install Fails**
```bash
# Check .npmrc configuration
npm run validate-npmrc
# If validation fails, setup token:
npm run setup-npmrc
# Test registry access
npm ping --registry http://devops.ccn/CCN%20Platform%20Collection/_packaging/CCN.Platform/npm/registry/
```
2. **"Token expired" / Authentication Fails**
```bash
# Get new token from CCN DevOps Portal
# Update .npmrc with new token:
npm run setup-npmrc
# Verify token works:
npm run validate-npmrc
```
3. **CCN Logging not working**
```bash
# Check configuration
echo $CCN_LOGGING_ENABLED
echo $CCN_LOGGING_ENDPOINT
# Check network connectivity
curl $CCN_LOGGING_ENDPOINT/health
```
4. **Performance issues**
```bash
# Disable body logging
CCN_LOG_REQUEST_BODY=false
CCN_LOG_RESPONSE_BODY=false
```
5. **Missing logs**
```bash
# Check log levels
CCN_LOG_LEVEL_SUCCESS=Level3
CCN_LOG_LEVEL_REQUEST=Level4
```
### Debug Mode
```bash
# Enable debug logging
DEBUG=ccn-logging:*
LOG_LEVEL=debug
```
## 📚 Best Practices
1. **Environment-specific Configuration**
- Development: Disable atau minimal logging
- Staging: Enable dengan request body
- Production: Enable tanpa sensitive data
2. **Log Level Strategy**
- Level1: Critical errors saja
- Level2: Important business operations
- Level3: Success operations
- Level4: Debug dan detailed requests
3. **Performance Optimization**
- Disable body logging di production
- Use appropriate log levels
- Monitor CCN service performance
4. **Security Best Practices**
- Never log passwords atau tokens
- Sanitize all sensitive data
- Use environment variables untuk credentials
---
*CCN Logging integration adalah optional feature. Service akan tetap berjalan normal bahkan jika CCN Logging tidak tersedia.*