Home · Developers · Guides · Advanced Monitoring and Observability System

Operations

Advanced Monitoring and Observability System

Metrics and dashboards

Overview

The Advanced Monitoring and Observability System provides comprehensive monitoring, logging, and observability capabilities with metrics collection, distributed tracing, log aggregation, alerting, and dashboard visualization. The system includes advanced features such as alert notification channels (email, Slack, webhooks), OpenTelemetry-style distributed tracing with context propagation, and Prometheus-compatible metrics collection with aggregation and retention policies.

Components

AdvancedMonitoring

The advanced monitoring manager with comprehensive observability features.

Location: novacoder/monitoring/advanced.py

Key Features:

  • Metrics Collection: Counters, gauges, histograms with automatic aggregation
  • Distributed Tracing: Span-based tracing with parent-child relationships
  • Log Aggregation: Centralized log collection with filtering and querying
  • Alerting: Rule-based alerting with severity levels and status tracking
  • Event Callbacks: Subscribe to monitoring events for custom handling
  • Thread-Safe Operations: All operations are thread-safe for concurrent access

MonitoringManager

Central manager for all monitoring components.

Location: novacoder/monitoring/manager.py

Key Features:

  • Orchestrates all monitoring components
  • Manages alerts, logs, performance, user analytics, and dashboards
  • Provides overall statistics and configuration

MonitoringService

Kernel service that wires MonitoringManager, AdvancedMonitoring, AlertManager, and the OpenTelemetry exporter. get_advanced_monitoring() now lazy-initializes an AdvancedMonitoring instance and registers it with the global registry if initialize() has not yet been called. This prevents the TUI Monitoring page from crashing when it is mounted before the full service lifecycle has run.

AlertManager

Manages alerts and notifications.

Location: novacoder/monitoring/alerts.py

Key Features:

  • Alert rule management
  • Multiple notification channels (Email, Slack, Webhook)
  • Alert severity levels (Critical, High, Medium, Low, Info)
  • Alert status tracking (Active, Acknowledged, Resolved)
  • Notification routing based on severity
  • Custom notification filtering
  • Alert acknowledgment and resolution workflow
  • AlertDeliveryService for background alert delivery
  • Queue-based alert processing with background thread
  • Delivery history tracking with success/failure recording
  • Delivery statistics and monitoring
  • Configurable delivery interval

Documentation: Alert Notification Channels, Alert Delivery

LogAggregator

Aggregates and analyzes logs.

Location: novacoder/monitoring/log_aggregation.py

Key Features:

  • Log collection from multiple sources
  • Log filtering and querying
  • Log analysis and statistics
  • Log level management (Debug, Info, Warning, Error, Critical)

PerformanceMonitor

Monitors system performance metrics.

Location: novacoder/monitoring/performance.py

Key Features:

  • Metric collection (Counter, Gauge, Histogram)
  • Performance threshold management
  • Anomaly detection
  • Trend analysis

UserAnalytics

Tracks user behavior analytics.

Location: novacoder/monitoring/user_analytics.py

Key Features:

  • User session tracking
  • Activity type classification
  • User metrics calculation
  • Behavior analysis

Dashboard

Dashboard manager for visualization.

Location: novacoder/monitoring/dashboard.py

Key Features:

  • Dashboard configuration management
  • Widget system (gauge, line chart, bar chart, pie chart, table, stat card, log viewer, alert list, metric summary)
  • Dashboard templates (system overview, application monitoring, log analysis, performance monitoring, user analytics)
  • HTML rendering with SVG charts
  • JSON and HTML export functionality
  • API endpoints for dashboard data, rendering, and export
  • DashboardRenderer class for HTML generation
  • DashboardExporter class for JSON/HTML export

Documentation: Monitoring Dashboard

Distributed Tracing

OpenTelemetry-style distributed tracing with context propagation.

Location: novacoder/monitoring/tracing.py

Key Features:

  • Tracer and Span management
  • Trace context propagation (traceparent headers)
  • Multiple sampling strategies (Always, Never, Probability, TraceIDRatio, NameBased)
  • Span lifecycle management with context manager
  • Span events and attributes
  • TracerProvider for service-wide tracing
  • Prometheus-compatible export

Documentation: Distributed Tracing

Metrics Collection

Prometheus-compatible metrics collection with aggregation and retention policies.

Location: novacoder/monitoring/metrics.py

Key Features:

  • Counter, Gauge, Histogram, Summary metrics
  • Label support for multi-dimensional metrics
  • MetricsRegistry for central management
  • MetricsAggregator for time-based aggregation
  • MetricsRetentionPolicy for data retention
  • Prometheus format export
  • Thread-safe operations
  • MetricsStorageBackend for persistent metrics storage
  • In-memory and disk-based storage options
  • Time-based filtering and limit controls
  • Automatic retention management (10,000 samples per metric)
  • Storage statistics and metrics

Documentation: Metrics Collection, Metrics Storage

API Endpoints

GET /api/monitoring/dashboards

List available monitoring dashboard templates.

Response:

{
  "dashboards": {
    "system-overview": { /* dashboard config */ },
    "application-monitoring": { /* dashboard config */ },
    "log-analysis": { /* dashboard config */ }
  }
}

GET /api/monitoring/dashboards/{dashboard_id}

Get a specific dashboard with data.

Response:

{
  "dashboard_id": "system-overview",
  "name": "System Overview",
  "config": { /* dashboard config */ },
  "data": { /* widget data */ }
}

GET /api/monitoring/metrics/history

Get historical data for a specific metric.

Query Parameters: metric_name (required), hours (default: 24)

Response:

{
  "metric_name": "cpu_percent",
  "history": [
    { "timestamp": 1234567890, "value": 25.5 }
  ]
}

GET /api/monitoring/traces/{trace_id}

Get all spans in a trace.

Response:

{
  "trace_id": "trace-123",
  "spans": [
    { "span_id": "span-1", "operation": "op1", "duration": 100 }
  ]
}

GET /api/monitoring/logs

Query log entries with optional filtering.

Query Parameters: level (optional), source (optional), limit (default: 100)

Response:

{
  "logs": [
    { "timestamp": 1234567890, "level": "INFO", "message": "Log message" }
  ]
}

POST /api/monitoring/alert-rules

Add a new alert rule.

Response:

{
  "success": true,
  "rule_id": "rule-123"
}

DELETE /api/monitoring/alert-rules/{rule_id}

Remove an alert rule.

Response:

{
  "success": true
}

POST /api/monitoring/alerts/{alert_id}/acknowledge

Acknowledge an alert.

Response:

{
  "success": true
}

POST /api/monitoring/alerts/{alert_id}/resolve

Resolve an alert.

Response:

{
  "success": true
}

GET /api/monitoring/alerts

Returns all monitoring alerts.

GET /api/monitoring/statistics

Returns overall monitoring statistics.

GET /api/monitoring/opentelemetry/export

Export traces, metrics, and logs in OTLP-compatible JSON format.

POST /api/monitoring/opentelemetry/export

Write exported traces, metrics, and logs to a file path provided in the request body ({"file_path": "/path/to/export.json"}).

Usage Example

Advanced Monitoring System

from novacoder.monitoring import AdvancedMonitoring, MetricType, AlertSeverity, AlertStatus

# Create advanced monitoring manager
monitoring = AdvancedMonitoring()
monitoring.start()

# Record metrics
monitoring.record_metric('cpu_usage', 75.5, MetricType.GAUGE, unit='percent')
monitoring.increment_counter('request_count', 1.0)
monitoring.set_gauge('memory_usage', 512.0, unit='MB')

# Distributed tracing
span = monitoring.start_span('api_request', parent_span_id=None, metadata={'endpoint': '/api/users'})
# ... do work ...
monitoring.finish_span(span.span_id)

# Log aggregation
monitoring.add_log('info', 'User logged in', 'auth-service', metadata={'user_id': '123'})

# Alerting
from novacoder.monitoring.advanced import AlertRule
rule = AlertRule(
    name='High CPU Alert',
    metric_name='cpu_usage',
    condition='greater_than',
    threshold=80.0,
    severity=AlertSeverity.WARNING
)
monitoring.add_alert_rule(rule)

# Get monitoring statistics
stats = monitoring.get_monitoring_stats()
print(f"Total metrics: {stats['total_metrics']}")
print(f"Total spans: {stats['total_spans']}")
print(f"Total logs: {stats['total_logs']}")

monitoring.stop()

Traditional Monitoring Manager

from novacoder.monitoring.manager import MonitoringManager, MonitoringConfig
from novacoder.monitoring.alerts import AlertRule, AlertSeverity

# Create manager
config = MonitoringConfig()
manager = MonitoringManager(config)

# Create alert rule
rule = AlertRule(
    name="High CPU",
    condition="cpu_usage > 80",
    severity=AlertSeverity.HIGH
)
manager.add_alert_rule(rule)

# Record performance metric
manager.record_metric("cpu_usage", 75.5)

# Check for alerts
alerts = manager.get_alerts()
for alert in alerts:
    print(f"Alert: {alert.message}")

Integration

Service: MonitoringService in novacoder/monitoring/service.py

The monitoring system is integrated into the NovaApplication and accessible via:

  • Service container: container.resolve(MonitoringService)
  • API endpoints for alerts and statistics
  • Integration with kernel observability features

Service Integration Details

The monitoring service is registered in the application service order and follows the standard Nova Coder service lifecycle:

from novacoder.app import create_app
from novacoder.monitoring.service import MonitoringService

app = create_app()
app.start()

# Access the monitoring service
monitoring_service = app.container.resolve(MonitoringService)
manager = monitoring_service.get_manager()

# Get system statistics
stats = manager.get_overall_statistics()
print(f"Total metrics: {stats['total_metrics']}")
print(f"Active alerts: {stats['active_alerts']}")

API Integration

The monitoring system exposes the following REST API endpoints:

  • GET /api/monitoring/alerts - List all monitoring alerts
  • GET /api/monitoring/statistics - Get overall monitoring statistics
  • GET /api/monitoring/metrics - Get system metrics
  • Additional endpoints for alert management, log aggregation, and performance monitoring

Web UI Integration

The monitoring system is integrated into the web interface with:

  • Navigation menu item under "Administration" section
  • Real-time dashboard with metrics visualization
  • Alert management interface
  • Log aggregation and analysis
  • Performance monitoring and trend analysis

Location: novacoder/web/react/src/pages/Monitoring.tsx - renderMonitoring() function

Web UI Features:

  • System Metrics Cards: Display total alerts, active alerts, resolved alerts, and alerts by severity (critical, warning, info)
  • Service Health Table: View service status, health status, and messages for all Nova Coder services
  • Alerts Table: View all alerts with severity, message, timestamp, and resolution status
  • Monitoring Statistics Table: View all monitoring statistics and metrics
  • Real-time Data Loading: Asynchronous API calls to fetch monitoring data
  • Error Handling: User-friendly error display for failed API calls

Web UI API Integration:

  • GET /api/monitoring/statistics - Fetch overall monitoring statistics
  • GET /api/monitoring/alerts - Fetch all monitoring alerts
  • GET /api/health - Fetch system health metrics

Web UI Usage:

// The renderMonitoring() function is called when navigating to the Monitoring page
async function renderMonitoring(){
  // Render UI structure with metrics cards, service health table, alerts table, and statistics
  $('content').innerHTML = `...`;

  // Fetch data from API endpoints
  const [stats,health,alerts]=await Promise.all([
    api('/api/monitoring/statistics'),
    api('/api/health'),
    api('/api/monitoring/alerts')
  ]);

  // Update UI with fetched data
  set('monitoring-metrics', metricsHTML);
  set('monitoring-services', servicesHTML);
  set('monitoring-alerts', alertsHTML);
  set('monitoring-stats', statsHTML);
}

TUI Integration

The monitoring system is now fully integrated into the Terminal User Interface (TUI) with the MonitoringPage:

Location: novacoder/gui/tui_screens/monitoring_page.py - MonitoringPage class

TUI Features:

  • System Metrics: View CPU, memory, disk, and network metrics
  • Service Health: Monitor health status of all Nova Coder services
  • Alert Management: View and manage active alerts with severity levels
  • Real-time Updates: Auto-refresh every 5 seconds for live monitoring
  • Service Integration: Direct integration with MonitoringService via _get_service()

TUI Navigation:

  • Keyboard Shortcut: Shift+F8 to access Monitoring page
  • Sidebar Navigation: "Monitoring" button under "NEW SYSTEMS" section
  • Page Routing: Integrated into main TUI page navigation system

TUI Usage:

# The TUI page automatically loads metrics on mount
def on_mount(self) -> None:
    self._setup_tables()
    self._load_metrics()
    self._set_refresh_interval(5.0)  # Auto-refresh every 5 seconds

# Background loading with service integration
@work(thread=True)
def _load_metrics(self) -> None:
    from novacoder.monitoring.service import MonitoringService
    
    svc = _get_service(MonitoringService)
    if not svc:
        self.app.call_from_thread(self._show_error, "Monitoring service unavailable")
        return
    
    metrics = svc.manager.get_user_metrics()
    health = svc.manager.get_user_analytics()
    alerts = svc.manager.get_alerts()
    # Update tables with metrics, health status, and alerts

Alert Rules

CPU Usage

AlertRule(
    name="High CPU",
    condition="cpu_usage > 80",
    severity=AlertSeverity.HIGH
)

Memory Usage

AlertRule(
    name="High Memory",
    condition="memory_usage > 90",
    severity=AlertSeverity.CRITICAL
)

Response Time

AlertRule(
    name="Slow Response",
    condition="response_time > 5000",
    severity=AlertSeverity.MEDIUM
)

Dashboard Widgets

Chart Widget

DashboardWidget(
    name="CPU Usage",
    widget_type=WidgetType.CHART,
    config={"metric": "cpu_usage", "time_range": "1h"}
)

Gauge Widget

DashboardWidget(
    name="Memory Usage",
    widget_type=WidgetType.GAUGE,
    config={"metric": "memory_usage", "max": 100}
)

Table Widget

DashboardWidget(
    name="Recent Logs",
    widget_type=WidgetType.TABLE,
    config={"source": "logs", "limit": 10}
)

Benefits

  • System Visibility: Real-time monitoring of system health
  • Proactive Detection: Alert on issues before they become critical
  • Performance Optimization: Identify bottlenecks and optimize
  • Debugging Support: Detailed logs and traces for troubleshooting
  • User Insights: Understand user behavior and patterns
  • Custom Dashboards: Visualize metrics relevant to your needs

Configuration

Monitoring settings can be configured through the application configuration:

{
  "monitoring": {
    "enable_alerts": true,
    "enable_log_aggregation": true,
    "enable_performance_monitoring": true,
    "enable_user_analytics": true,
    "log_retention_days": 30,
    "metric_retention_days": 7,
    "alert_notification_channels": ["email", "slack"]
  }
}

See Also

  • Kernel Observability - Kernel-level observability
  • Health Monitoring - Health check system
  • API Analytics - API-specific analytics
  • Agent Monitoring - Agent performance monitoring
  • Distributed System Architecture - Distributed monitoring integration

Web UI Integration

The Monitoring system is fully integrated into the Nova Coder Web UI with a dedicated "Monitoring" navigation item under the Administration section.

Monitoring UI Features

The Monitoring UI provides:

  • Dashboard Selection: Choose from multiple dashboard templates (System Overview, Application Monitoring, Log Analysis)
  • Auto-Refresh Settings: Configure automatic refresh intervals (Off, 30s, 1m, 5m)
  • Real-Time Metrics Display: CPU, memory, and disk usage metrics in real-time
  • System Health Display: Service status and health indicators
  • Alerts Display: List of monitoring alerts with severity, message, timestamp, and status
  • Monitoring Statistics: Overall monitoring statistics and metrics

API Endpoints Used

The Monitoring UI integrates with the following API endpoints:

  • GET /api/monitoring/alerts - List all monitoring alerts
  • GET /api/monitoring/statistics - Get overall monitoring statistics
  • GET /api/monitoring/dashboards - List available dashboard templates
  • GET /api/monitoring/dashboards/{dashboard_id} - Get specific dashboard configuration
  • GET /api/monitoring/metrics - Get real-time system metrics
  • GET /api/monitoring/metrics/history/{metric_name} - Get historical metric data
  • GET /api/monitoring/traces/{trace_id} - Get distributed trace data
  • GET /api/monitoring/logs - Query log entries with filters
  • POST /api/monitoring/alerts/rules - Add alert rule
  • DELETE /api/monitoring/alerts/rules/{rule_id} - Remove alert rule
  • POST /api/monitoring/alerts/{alert_id}/acknowledge - Acknowledge alert
  • POST /api/monitoring/alerts/{alert_id}/resolve - Resolve alert

UI Navigation

Access the Monitoring UI by:

  1. Navigate to the Administration section in the sidebar
  2. Click on "Monitoring"
  3. The UI displays monitoring dashboard, metrics, alerts, and statistics

JavaScript Integration

The Monitoring UI is implemented in novacoder/web/react/src/pages/Monitoring.tsx with the following functions:

  • renderMonitoring() - Main render function for the Monitoring page
  • loadRealTimeMetrics() - Load and display real-time system metrics
  • loadMonitoringDashboard() - Load and display selected dashboard
  • loadMonitoringAlerts() - Load and display monitoring alerts

Response Handling

The UI handles API responses according to the actual response structure from each endpoint:

  • Monitoring Statistics: Expects stats.data||stats with total_alerts, active_alerts, resolved_alerts, critical_alerts, warning_alerts, info_alerts
  • Monitoring Alerts: Expects alerts.data?.alerts||alerts.alerts||[] with severity, message, timestamp, resolved fields
  • Real-Time Metrics: Expects r.data||r with cpu, memory, disk objects containing percent, count, used, total fields
  • Dashboard Data: Expects r.data||r with config and data objects

OpenTelemetry Export (React UI)

The Monitoring page (/monitoring) includes a dedicated OpenTelemetry Export card:

  • Export OpenTelemetry JSON - Calls GET /api/monitoring/opentelemetry/export and displays the OTLP-formatted JSON response.
  • Export to File - Calls POST /api/monitoring/opentelemetry/export with an optional path field and shows the written file path.

Both controls are wired to useAccessibility for screen-reader announcements and display results in keyboard-focusable <pre> blocks.

Source: wiki/monitoring-system.md · rendered 2026-11-10