Toto App Monitoring Integration Setup Guide
Overview
This guide explains how to integrate toto-app monitoring data with toto-bo's monitoring dashboard. The integration allows you to monitor performance, errors, logs, and user activity from toto-app directly in the toto-bo backoffice.
Architecture
toto-app (Main App)
├── Client-side monitoring utilities
├── Performance metrics collection
├── Error reporting
├── User activity tracking
└── Data sent to toto-bo APIs
toto-bo (Backoffice)
├── Monitoring API endpoints
├── Firestore data storage
├── Real-time dashboard
└── Alert system
Setup Steps
1. Install Dependencies in toto-app
Add the monitoring utilities to your toto-app project:
# In toto-app directory
npm install @toto/monitoring-utils
2. Configure toto-app Monitoring
Create a monitoring configuration file in toto-app:
// toto-app/src/lib/monitoring.ts
import { clientMonitoring, recordPerformance, recordError, recordLog, recordActivity } from '@toto/monitoring-utils';
// Initialize monitoring
const monitoring = clientMonitoring;
// Set user ID when user logs in
export const setUserId = (userId: string) => {
monitoring.setUserId(userId);
};
// Export monitoring functions
export { recordPerformance, recordError, recordLog, recordActivity };
3. Integrate with Existing Performance Monitoring
Update your existing performance monitoring in toto-app:
// toto-app/src/utils/performanceMonitor.ts
import { recordPerformance } from '@/lib/monitoring';
// In your existing PerformanceMonitor class
private recordMetric(name: string, value: number, rating: 'good' | 'needs-improvement' | 'poor'): void {
// ... existing code ...
// Send to toto-bo monitoring
recordPerformance(name, value, rating);
}
4. Integrate Error Reporting
Update your error reporting in toto-app:
// toto-app/src/utils/errorReporting.ts
import { recordError } from '@/lib/monitoring';
export const reportError = (error: Error, context?: string) => {
// ... existing error reporting ...
// Send to toto-bo monitoring
recordError(
error.message,
error.stack,
context,
'high' // severity
);
};
5. Add User Activity Tracking
Track user interactions in toto-app:
// toto-app/src/hooks/useUserActivity.ts
import { recordActivity } from '@/lib/monitoring';
export const useUserActivity = () => {
const trackPageView = (page: string) => {
recordActivity('page_view', page, { timestamp: Date.now() });
};
const trackButtonClick = (button: string, page: string) => {
recordActivity('button_click', button, { page, timestamp: Date.now() });
};
const trackFormSubmit = (form: string, success: boolean) => {
recordActivity('form_submit', form, { success, timestamp: Date.now() });
};
return { trackPageView, trackButtonClick, trackFormSubmit };
};
6. Configure API Endpoints
Update your toto-app API configuration to point to toto-bo:
// toto-app/src/config/monitoring.ts
export const MONITORING_CONFIG = {
baseUrl: process.env.NODE_ENV === 'production'
? 'https://bo.betoto.pet/api/monitoring'
: 'http://localhost:3000/api/monitoring',
batchSize: 10,
flushInterval: 30000
};
7. Environment Variables
Add the following environment variables to toto-app:
# toto-app/.env.local
NEXT_PUBLIC_MONITORING_BASE_URL=https://bo.betoto.pet/api/monitoring
NEXT_PUBLIC_APP_VERSION=1.0.0
NEXT_PUBLIC_ENVIRONMENT=production
8. Initialize Monitoring in toto-app
Add monitoring initialization to your toto-app:
// toto-app/src/pages/_app.tsx
import { useEffect } from 'react';
import { clientMonitoring } from '@/lib/monitoring';
export default function App({ Component, pageProps }) {
useEffect(() => {
// Initialize monitoring
clientMonitoring.setUserId(getCurrentUserId());
// Track app initialization
clientMonitoring.recordActivity('app_initialized', 'App', {
version: process.env.NEXT_PUBLIC_APP_VERSION,
environment: process.env.NEXT_PUBLIC_ENVIRONMENT
});
}, []);
return <Component {...pageProps} />;
}
Monitoring Dashboard Usage
1. Access the Dashboard
Navigate to the monitoring dashboard in toto-bo:
- Go to
/dashboard/monitoring - Select environment (production/staging)
- Choose time range (1h, 24h, 7d, 30d)
2. Dashboard Sections
Overview Tab
- System health status
- Active users count
- Performance score
- Recent alerts
Performance Tab
- Core Web Vitals (LCP, FID, CLS)
- Performance trends
- Page load times
Errors Tab
- Error rate and trends
- Top errors by frequency
- Error severity distribution
Logs Tab
- Log volume and trends
- Logs by level (debug, info, warn, error, critical)
- Recent log entries
System Tab
- System uptime and health checks
- Resource utilization (CPU, memory, disk)
- API response times
3. Real-time Updates
The dashboard automatically refreshes every 30 seconds. You can also manually refresh using the refresh button.
Data Collection
Performance Metrics
The system automatically collects:
- LCP (Largest Contentful Paint): Time to render the largest content
- FID (First Input Delay): Time from first user interaction to response
- CLS (Cumulative Layout Shift): Visual stability score
- Custom metrics: Any custom performance measurements
Error Tracking
Errors are automatically tracked with:
- Error message and stack trace
- Component where error occurred
- User context and session information
- Severity level (low, medium, high, critical)
User Activity
User interactions are tracked including:
- Page views and navigation
- Button clicks and form submissions
- Feature usage and engagement
- Session duration and patterns
Application Logs
Structured logging with:
- Log levels (debug, info, warn, error, critical)
- Contextual information
- Component and action tracking
- Metadata and custom fields
Alerting
Alert Types
The system can generate alerts for:
- Performance: LCP > 2.5s, FID > 100ms, CLS > 0.1
- Errors: Error rate > 5%, Critical errors
- System: App down, High response times
- User Activity: Unusual traffic patterns
Alert Configuration
Alerts are configured in the monitoring dashboard and can be:
- In-app notifications
- Email alerts (for critical issues)
- Slack integration (future)
Troubleshooting
Common Issues
-
No data appearing in dashboard
- Check if toto-app is sending data to correct API endpoints
- Verify environment variables are set correctly
- Check browser console for errors
-
Performance metrics not updating
- Ensure performance monitoring is enabled in toto-app
- Check if batch size and flush interval are appropriate
- Verify API endpoints are accessible
-
Error reports not showing
- Check error reporting integration in toto-app
- Verify error severity levels are set correctly
- Check Firestore permissions
Debug Mode
Enable debug mode in toto-app to see monitoring data being sent:
// toto-app/src/lib/monitoring.ts
const monitoring = new ClientMonitoringUtils(
process.env.NEXT_PUBLIC_MONITORING_BASE_URL,
1, // batch size
5000 // flush interval
);
// Enable debug logging
if (process.env.NODE_ENV === 'development') {
monitoring.enableDebugMode();
}
Security Considerations
Data Privacy
- User data is anonymized in monitoring metrics
- Personal information is not stored in monitoring data
- Session IDs are used instead of user IDs where possible
Access Control
- Monitoring dashboard requires admin permissions
- API endpoints are protected with authentication
- Data is encrypted in transit and at rest
Rate Limiting
- API endpoints have rate limiting to prevent abuse
- Batch processing reduces API calls
- Automatic retry with exponential backoff
Performance Impact
Client-side Impact
- Minimal performance impact (< 1ms per metric)
- Batched data transmission reduces network overhead
- Automatic cleanup prevents memory leaks
Server-side Impact
- Efficient Firestore queries with proper indexing
- Cached data for dashboard display
- Optimized data aggregation and processing
Future Enhancements
Planned Features
- Real-time WebSocket updates
- Advanced alerting rules
- Custom dashboard widgets
- Historical data analysis
- Mobile app monitoring
- Integration with external monitoring services
Customization
- Custom metric definitions
- Personalized alert thresholds
- Custom dashboard layouts
- Export capabilities for reports
Support
For issues or questions about the monitoring integration:
- Check this guide for common solutions
- Review the API documentation
- Check the monitoring dashboard for system status
- Contact the development team for advanced issues
API Reference
Performance Metrics API
POST /api/monitoring/app-performance
Content-Type: application/json
{
"metrics": [
{
"name": "lcp",
"value": 1200,
"rating": "good",
"timestamp": 1640995200000,
"url": "https://app.betoto.pet/dashboard",
"userAgent": "Mozilla/5.0...",
"userId": "user123",
"sessionId": "session456"
}
]
}
Error Reporting API
POST /api/monitoring/app-errors
Content-Type: application/json
{
"message": "ChunkLoadError: Loading chunk 2 failed",
"stack": "Error: Loading chunk 2 failed\n at HTMLScriptElement...",
"componentStack": "in App (at pages/_app.tsx:45)",
"timestamp": "2024-01-01T12:00:00.000Z",
"userAgent": "Mozilla/5.0...",
"url": "https://app.betoto.pet/dashboard",
"errorId": "error_1640995200000_abc123",
"retryCount": 0,
"userId": "user123",
"severity": "high"
}
Log Entry API
POST /api/monitoring/app-logs
Content-Type: application/json
{
"level": "info",
"message": "User logged in successfully",
"context": {
"userId": "user123",
"sessionId": "session456",
"component": "LoginForm",
"action": "login",
"metadata": {
"loginMethod": "email"
},
"url": "https://app.betoto.pet/login",
"userAgent": "Mozilla/5.0..."
},
"timestamp": "2024-01-01T12:00:00.000Z"
}
User Activity API
POST /api/monitoring/app-user-activity
Content-Type: application/json
{
"activities": [
{
"userId": "user123",
"sessionId": "session456",
"action": "page_view",
"component": "Dashboard",
"url": "https://app.betoto.pet/dashboard",
"timestamp": 1640995200000,
"metadata": {
"pageTitle": "Dashboard",
"referrer": "https://app.betoto.pet/login"
}
}
]
}