### Example HttpCollector Configuration Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/configuration.md Example of configuring the httpCollector with custom maxRecords and windowMs. ```typescript import { httpCollector } from 'adonisjs-server-stats/collectors' collectors: [ httpCollector({ maxRecords: 50_000, windowMs: 30_000 }) ] ``` -------------------------------- ### async start(): Promise Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/stats-engine.md Initializes all configured collectors by calling their start() method. This is typically called once by the provider during the app's ready phase. ```APIDOC ## async start(): Promise ### Description Initialize all collectors by calling each collector's `start()` method (if defined) sequentially. Called once by the provider during the `ready` phase. Logs a list of started collectors to console. Errors during collector startup are logged as warnings but don't halt the engine. ### Method Signature ```ts async start(): Promise ``` ### Throws Does not throw. Errors during collector startup are logged as warnings. ### Example ```ts await engine.start() // Logs: "[server-stats] collectors started: process, http, redis, ..." ``` ``` -------------------------------- ### Start LogStreamService Monitoring Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/prometheus-and-log-stream.md Example of starting the LogStreamService to monitor a log file. This method opens the file and begins watching for new entries. ```typescript const service = new LogStreamService('logs/app.log') await service.start() ``` -------------------------------- ### Example DbPoolCollector Configuration Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/configuration.md Example of configuring the dbPoolCollector to monitor the 'postgres' Lucid connection. ```typescript import { dbPoolCollector } from 'adonisjs-server-stats/collectors' collectors: [ dbPoolCollector({ connectionName: 'postgres' }) ] ``` -------------------------------- ### GET /admin/api/debug/config Response Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns the current debug store configuration settings. ```json { "enabled": true, "maxQueries": 500, "maxEvents": 200, "maxEmails": 100, "slowQueryThresholdMs": 100, "persistDebugData": false, "tracing": true, "maxTraces": 200, "dashboard": true, "dashboardPath": "/__stats", "retentionDays": 7, "dbPath": ".adonisjs/server-stats/dashboard.sqlite3", "debugEndpoint": "/admin/api/debug" } ``` -------------------------------- ### Install better-sqlite3 Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/README.md Install the better-sqlite3 package, which is required for local data storage by the dashboard. ```bash npm install better-sqlite3 ``` -------------------------------- ### Example LogCollector Configurations Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/configuration.md Examples of configuring the logCollector, either by auto-detecting the Pino logger or specifying a custom log file path. ```typescript import { logCollector } from 'adonisjs-server-stats/collectors' // Auto-detect Pino logger collectors: [logCollector()] // Or specify a custom log file collectors: [logCollector({ logPath: 'tmp/app.log' })] ``` -------------------------------- ### Example QueueCollector Configuration Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/configuration.md Example of configuring the queueCollector using environment variables for Redis connection details. ```typescript import env from '#start/env' import { queueCollector } from 'adonisjs-server-stats/collectors' collectors: [ queueCollector({ queueName: 'default', connection: { host: env.get('QUEUE_REDIS_HOST'), port: env.get('QUEUE_REDIS_PORT'), password: env.get('QUEUE_REDIS_PASSWORD'), }, }) ] ``` -------------------------------- ### GET /__stats/api/overview Response Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns overview metrics for the dashboard, optionally filtered by a time range. ```json { "avgResponseTime": 150, "p95ResponseTime": 500, "requestsPerMinute": 720, "errorRate": 0.5, "uptime": 86400, "topSlowQueries": [ { "sql": "SELECT...", "duration": 500 } ] } ``` -------------------------------- ### Instantiate and Start LogStreamService Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/prometheus-and-log-stream.md Create a new instance of LogStreamService, providing the log file path and an optional entry callback. Then, start the service to begin monitoring. ```typescript import { LogStreamService } from 'adonisjs-server-stats/log-stream' const service = new LogStreamService('logs/app.log', (entry) => { console.log(`[${entry.level}] ${entry.message}`) }) await service.start() // later... service.stop() ``` -------------------------------- ### Install adonisjs-server-stats Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/README.md Install the package using npm. ```bash npm install adonisjs-server-stats ``` -------------------------------- ### Zero-Config Setup for AdonisJS Server Stats Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/announcement-1.6.md This snippet shows the minimal configuration required for adonisjs-server-stats. Collectors are auto-detected based on installed packages, simplifying setup. ```typescript import { defineConfig } from 'adonisjs-server-stats' export default defineConfig({}) ``` -------------------------------- ### Example: Retrieving and Logging Recent Entries Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/prometheus-and-log-stream.md Shows how to get the last 10 log entries and iterate through them to log their level, timestamp, and message. ```typescript const recent = service.getLogs(10) // Last 10 entries recent.forEach(entry => { console.log(`${entry.level} @ ${entry.timestamp}: ${entry.message}`) }) ``` -------------------------------- ### GET /__stats/api/queries Response Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns a paginated list of database queries, including SQL, duration, and timestamp. ```json { "items": [ { "id": 1, "sql": "SELECT...", "duration": 45, "timestamp": 1700000000000 } ], "total": 5000, "page": 1, "perPage": 50, "lastPage": 100 } ``` -------------------------------- ### Fetch Server Stats Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md This example demonstrates how to fetch the server stats JSON from the /admin/api/server-stats endpoint and access a specific metric like cpuPercent. ```typescript // From the stats bar fetch('/admin/api/server-stats') .then(r => r.json()) .then(stats => console.log(stats.cpuPercent)) ``` -------------------------------- ### GET /__stats/api/filters - Response Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Example JSON response for retrieving saved filters. This endpoint returns a list of filters with their IDs, names, types, and filter configurations. ```json { "items": [ { "id": 1, "name": "My slow queries", "type": "queries", "filters": { "minDuration": 500 } } ] } ``` -------------------------------- ### GET /admin/api/debug/traces Response Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns request traces with log correlation. Supports pagination via query parameters. ```json { "traces": [ { "id": 1, "method": "GET", "url": "/users/123", "statusCode": 200, "totalDuration": 125.5, "spanCount": 3, "spans": [ { "id": "1", "parentId": null, "label": "SELECT * FROM users", "category": "db", "startOffset": 10, "duration": 45.2, "metadata": {} } ], "warnings": [], "timestamp": 1700000000000 } ], "total": 100, "page": 1, "perPage": 50, "lastPage": 2 } ``` -------------------------------- ### GET /admin/api/debug/diagnostics Response Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns diagnostics information for various providers and collector health status. ```json { "collectors": [ { "name": "process", "label": "process — cpu, memory, event loop, uptime", "status": "healthy", "lastError": null, "lastErrorAt": null }, { "name": "http", "label": "http — buffer: 10,000, window: 60s", "status": "healthy", "lastError": null, "lastErrorAt": null } ], "features": { "lucid": true, "redis": true, "bullmq": true, "transmit": true, "betterSqlite3": true } } ``` -------------------------------- ### Zero-Config Setup for AdonisJS Server Stats Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/announcement-1.6.md This snippet demonstrates the minimal configuration required for AdonisJS Server Stats. The library automatically detects installed packages and enables relevant collectors without explicit configuration. ```typescript import { defineConfig } from 'adonisjs-server-stats' export default defineConfig({}) // That's it. Everything is auto-detected. ``` -------------------------------- ### Prometheus Query Examples Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/prometheus-and-log-stream.md Examples of PromQL queries to retrieve various server statistics, including CPU usage, response times, error rates, and database pool pressure. ```promql # CPU usage (%) server_stats_cpu_percent ``` ```promql # Average response time trend rate(server_stats_avg_response_time_ms[5m]) ``` ```promql # Error rate > 1% server_stats_error_rate > 1 ``` ```promql # Low Redis hit rate alert server_stats_redis_hit_rate < 80 ``` ```promql # Database pool pressure server_stats_db_pool_pending > 0 ``` -------------------------------- ### GET /__stats/api/overview/chart Response Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns time-series chart data for dashboard metrics, optionally filtered by a time range. ```json { "labels": ["12:00", "12:01", "12:02"], "datasets": [ { "label": "Response Time (ms)", "data": [150, 160, 145] }, { "label": "Requests/min", "data": [720, 730, 710] } ] } ``` -------------------------------- ### Server Stats Configuration Source Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/middleware-and-provider.md Example of the configuration file structure for server stats. ```typescript // config/server_stats.ts import { defineConfig } from 'adonisjs-server-stats' export default defineConfig({ // All options documented in Configuration reference }) ``` -------------------------------- ### Start StatsEngine Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/stats-engine.md Initializes all configured collectors. This method is called automatically by the provider during the application's 'ready' phase. ```typescript await engine.start() // Logs: "[server-stats] collectors started: process, http, redis, ..." ``` -------------------------------- ### Install Server Stats Package Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/README.md Install the main package for AdonisJS Server Stats. Peer dependencies for React, Vue, or real-time updates can be installed separately if needed. ```bash npm install adonisjs-server-stats ``` ```bash # React npm install react react-dom # Vue npm install vue # Real-time updates (optional — falls back to polling) npm install @adonisjs/transmit-client ``` -------------------------------- ### StatsEngine Constructor Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/stats-engine.md Instantiates a StatsEngine with an array of metric collectors. Ensure all necessary collectors are imported and initialized. ```typescript import { StatsEngine } from 'adonisjs-server-stats' import { processCollector, systemCollector, httpCollector, } from 'adonisjs-server-stats/collectors' const engine = new StatsEngine([ processCollector(), systemCollector(), httpCollector(), ]) ``` -------------------------------- ### GET /__stats/api/requests/:id Response Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns detailed information for a specific request, including associated queries and trace data. ```json { "id": 1, "method": "GET", "url": "/users/123", "statusCode": 200, "duration": 125, "queries": [ /* associated queries */ ], "trace": { /* trace record */ }, "timestamp": 1700000000000 } ``` -------------------------------- ### Example: Accessing Log Statistics Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/prometheus-and-log-stream.md Demonstrates how to call getLogStats() and log the number of errors in the last 5 minutes. ```typescript const stats = service.getLogStats() console.log(`${stats.errorsLast5m} errors in last 5 minutes`) ``` -------------------------------- ### Custom Disk Collector Implementation Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/README.md Example of creating a custom MetricCollector for disk space monitoring. ```typescript import type { MetricCollector } from 'adonisjs-server-stats' function diskCollector(): MetricCollector { return { name: 'disk', async collect() { const { availableSpace, totalSpace } = await getDiskInfo() return { diskAvailableGb: availableSpace / 1e9, diskTotalGb: totalSpace / 1e9, diskUsagePercent: ((totalSpace - availableSpace) / totalSpace) * 100, } }, } } ``` -------------------------------- ### POST /__stats/api/filters - Request Body Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Example JSON request body for creating a new saved filter. Requires name, type, and filter details. ```json { "name": "My slow queries", "type": "queries", "filters": { "minDuration": 500 } } ``` -------------------------------- ### GET /__stats/api/traces Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves a paginated list of application traces. ```APIDOC ## GET /__stats/api/traces ### Description Returns paginated trace list. ### Method GET ### Endpoint /__stats/api/traces ### Response #### Success Response (200) - **items** (array) - A list of trace objects. - **id** (integer) - The trace ID. - **method** (string) - The HTTP method of the request. - **url** (string) - The URL of the request. - **statusCode** (integer) - The HTTP status code of the response. - **totalDuration** (integer) - The total duration of the trace in milliseconds. - **spanCount** (integer) - The number of spans in the trace. - **timestamp** (integer) - The Unix timestamp when the trace occurred. - **total** (integer) - The total number of traces. - **page** (integer) - The current page number. - **perPage** (integer) - The number of items per page. - **lastPage** (integer) - The last page number. ### Response Example ```json { "items": [ { "id": 1, "method": "GET", "url": "/users", "statusCode": 200, "totalDuration": 125, "spanCount": 3, "timestamp": 1700000000000 } ], "total": 1000, "page": 1, "perPage": 50, "lastPage": 20 } ``` ``` -------------------------------- ### Example Server Stats Configuration Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/specs/dashboard-page.md Demonstrates how to configure the server stats module within the AdonisJS application configuration file. ```typescript // config/server_stats.ts export default defineConfig({ devToolbar: { enabled: true, tracing: true, dashboard: true, dashboardPath: '/__stats', retentionDays: 7, dbPath: 'tmp/server-stats.sqlite3', }, // ... }) ``` -------------------------------- ### POST /__stats/api/filters - Response Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Example JSON response after successfully creating a saved filter. Returns the details of the newly created filter, including its assigned ID. ```json { "id": 1, "name": "My slow queries", "type": "queries", "filters": {} } ``` -------------------------------- ### GET /__stats/api/queries/:id/explain Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns the EXPLAIN plan for a specific query, useful for optimizing query performance. ```APIDOC ## GET /__stats/api/queries/:id/explain ### Description Returns EXPLAIN plan for a query (SELECT only). ### Method GET ### Endpoint /__stats/api/queries/:id/explain ### Parameters #### Path Parameters - **id** (URL) — query ID ### Response #### Success Response (200) - **plan** (array) - An array of EXPLAIN plan steps. - **QUERY PLAN** (string) - Description of the query plan step. ### Response Example ```json { "plan": [ { "QUERY PLAN": "Seq Scan on users..." } ] } ``` ``` -------------------------------- ### Add System Collector to Configuration Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/collectors.md Demonstrates adding the system collector to your application's collector setup. ```typescript import { systemCollector } from 'adonisjs-server-stats/collectors' collectors: [systemCollector()] ``` -------------------------------- ### Add Process Collector to Configuration Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/collectors.md Example of how to include the process collector in your application's collector configuration. ```typescript import { processCollector } from 'adonisjs-server-stats/collectors' collectors: [processCollector()] ``` -------------------------------- ### Get Application Configuration Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns the application's configuration settings. Sensitive information like secrets is redacted. ```json { "app": { "appKey": "***", "nodeEnv": "development" }, "database": { "postgres": { "host": "localhost", "password": "***" } } } ``` -------------------------------- ### GET /admin/api/debug/config Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves the current debug store configuration settings for the server. ```APIDOC ## GET /admin/api/debug/config ### Description Returns debug store configuration (internal). ### Method GET ### Endpoint /admin/api/debug/config ### Response #### Success Response (200) - **enabled** (boolean) - Whether debug mode is enabled. - **maxQueries** (integer) - Maximum number of queries to store. - **maxEvents** (integer) - Maximum number of events to store. - **maxEmails** (integer) - Maximum number of emails to store. - **slowQueryThresholdMs** (integer) - Threshold for slow queries in milliseconds. - **persistDebugData** (boolean) - Whether to persist debug data. - **tracing** (boolean) - Whether tracing is enabled. - **maxTraces** (integer) - Maximum number of traces to store. - **dashboard** (boolean) - Whether the dashboard is enabled. - **dashboardPath** (string) - The path to the dashboard. - **retentionDays** (integer) - Data retention period in days. - **dbPath** (string) - Path to the debug database. - **debugEndpoint** (string) - The debug API endpoint. ### Response Example ```json { "enabled": true, "maxQueries": 500, "maxEvents": 200, "maxEmails": 100, "slowQueryThresholdMs": 100, "persistDebugData": false, "tracing": true, "maxTraces": 200, "dashboard": true, "dashboardPath": "/__stats", "retentionDays": 7, "dbPath": ".adonisjs/server-stats/dashboard.sqlite3", "debugEndpoint": "/admin/api/debug" } ``` **Status Codes:** `200`, `403` ``` -------------------------------- ### GET /__stats/api/overview Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves an overview of key server performance metrics, such as response time and request rate. ```APIDOC ## GET /__stats/api/overview ### Description Returns overview metrics. ### Method GET ### Endpoint /__stats/api/overview ### Parameters #### Query Parameters - **range** (string) - Optional - time range, e.g., `'1h'`, `'6h'`, `'24h'`, `'7d'` ### Response #### Success Response (200) - **avgResponseTime** (number) - Average response time in milliseconds. - **p95ResponseTime** (number) - 95th percentile response time in milliseconds. - **requestsPerMinute** (integer) - Number of requests per minute. - **errorRate** (number) - The rate of errors. - **uptime** (integer) - Uptime in seconds. - **topSlowQueries** (array) - List of top slow queries. ### Response Example ```json { "avgResponseTime": 150, "p95ResponseTime": 500, "requestsPerMinute": 720, "errorRate": 0.5, "uptime": 86400, "topSlowQueries": [ { "sql": "SELECT...", "duration": 500 } ] } ``` **Status Codes:** `200`, `403` ``` -------------------------------- ### Get Query Explain Plan Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns the EXPLAIN plan for a specific query ID. This helps in understanding how the database executes a query. ```json { "plan": [ { "QUERY PLAN": "Seq Scan on users..." } ] } ``` -------------------------------- ### Verbose Logging Output Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/middleware-and-provider.md When verbose logging is enabled, the provider outputs detailed information about its boot process, including configuration loading, collector status, and route registration. ```text [server-stats] config loaded: /config/server_stats.ts [server-stats] auto-detected collectors... [server-stats] collectors started: process, http, redis, ... [server-stats] debug store initialized: .adonisjs/server-stats/dashboard.sqlite3 [server-stats] trace collector enabled [server-stats] auto-registered routes: /admin/api/server-stats, /admin/api/debug/*, /__stats/* [server-stats] collection timer started: every 3000ms [server-stats] realtime updates enabled via Transmit ``` -------------------------------- ### Prometheus Collector Setup Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/prometheus-and-log-stream.md This snippet shows how to set up the Prometheus server stats collector in your AdonisJS application configuration. ```APIDOC ## Prometheus Collector Setup ### Description Configure your AdonisJS application to export server statistics as Prometheus gauges by adding the `serverStatsCollector()` to your Prometheus configuration. ### Configuration File `config/prometheus.ts` ### Code ```ts import { defineConfig } from '@julr/adonisjs-prometheus' import { httpCollector } from '@julr/adonisjs-prometheus/collectors/http_collector' import { serverStatsCollector } from 'adonisjs-server-stats/prometheus' export default defineConfig({ endpoint: '/metrics', collectors: [ httpCollector(), serverStatsCollector(), // ← Add this line ], }) ``` ### Notes Requires `@julr/adonisjs-prometheus` as a peer dependency. ``` -------------------------------- ### Get Paginated Trace List Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves a paginated list of application traces. Useful for performance analysis and debugging distributed systems. ```json { "items": [ { "id": 1, "method": "GET", "url": "/users", "statusCode": 200, "totalDuration": 125, "spanCount": 3, "timestamp": 1700000000000 } ], "total": 1000, "page": 1, "perPage": 50, "lastPage": 20 } ``` -------------------------------- ### Example: ServerStatsBar in React Layout Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/edge-and-components.md Integrate the ServerStatsBar component into your main React layout component to display stats persistently. ```tsx // In your layout component import { ServerStatsBar } from 'adonisjs-server-stats/react' import 'adonisjs-server-stats/react/css' export default function Layout({ children }) { return (
{/* ... */}
{children}
) } ``` -------------------------------- ### GET /__stats/api/requests Response Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns paginated request history, with optional filtering by HTTP method and status code. ```json { "items": [ { "id": 1, "method": "GET", "url": "/users", "statusCode": 200, "duration": 125, "timestamp": 1700000000000 } ], "total": 1000, "page": 1, "perPage": 50, "lastPage": 20 } ``` -------------------------------- ### Basic Server Stats Configuration Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/README.md Create a basic configuration file for server stats. ```typescript // config/server_stats.ts import { defineConfig } from 'adonisjs-server-stats' export default defineConfig({}) ``` -------------------------------- ### GET /admin/api/debug/traces/:id Response Example Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns trace detail with spans and related logs for a specific trace ID. ```json { "id": 1, "method": "GET", "url": "/users/123", "statusCode": 200, "totalDuration": 125.5, "spanCount": 3, "spans": [ /* all spans */ ], "warnings": [], "logs": [ /* correlated log entries */ ], "httpRequestId": "req-abc123", "timestamp": 1700000000000 } ``` -------------------------------- ### Execute EXPLAIN on SELECT Queries Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/specs/dashboard-page.md Example of executing an EXPLAIN query on a SELECT statement using the application's default database connection. This is used to retrieve query execution plans. ```sql EXPLAIN {sql} ``` -------------------------------- ### Get Route Table Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns a list of all registered routes in the application. Useful for understanding the application's API surface. ```json { "items": [ { "method": "GET", "pattern": "/users/:id", "name": "users.show", "handler": "UsersController.show", "middleware": ["auth", "throttle:60,1"] } ] } ``` -------------------------------- ### Configure HTTP Collector with Different Options Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/collectors.md Examples showing default HTTP collector initialization and configurations with a larger record buffer or a shorter rolling window for rate calculations. ```typescript import { httpCollector } from 'adonisjs-server-stats/collectors' collectors: [ httpCollector() // defaults httpCollector({ maxRecords: 50_000 }) // larger buffer httpCollector({ windowMs: 30_000 }) // 30-second window ] ``` -------------------------------- ### Importing Main Entry Point Modules Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/README.md Import core modules for initializing and managing server stats, including configuration definition, stats engine, request metrics, dashboard store, and tracing functionalities. ```typescript import { defineConfig, StatsEngine, RequestMetrics, DashboardStore, trace, } from 'adonisjs-server-stats' ``` -------------------------------- ### Define Server Stats Configuration Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/configuration.md Use the defineConfig function to set up server stats. This example configures a poll interval, an authorization callback, and enables both the toolbar and dashboard. ```typescript import { defineConfig } from 'adonisjs-server-stats' export default defineConfig({ pollInterval: 3000, authorize: (ctx) => ctx.auth?.user?.role === 'admin', toolbar: true, dashboard: true, }) ``` -------------------------------- ### Initialize System Collector Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/collectors.md Reports OS-level metrics such as load averages, memory usage, and system uptime. This collector requires no options. ```typescript import { systemCollector } from 'adonisjs-server-stats/collectors' const collector = systemCollector() ``` -------------------------------- ### Enable Dashboard Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/README.md Enable the dashboard by setting the `dashboard` option to `true` in your configuration file. Restart your dev server to access it at `/__stats`. ```typescript // config/server_stats.ts export default defineConfig({ dashboard: true, }) ``` -------------------------------- ### Start and Stop Log Stream Service Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/README.md Instantiate and manage the LogStreamService to watch a log file and process new entries. Ensure to call `start()` to begin watching and `stop()` to clean up resources. ```typescript import { LogStreamService } from 'adonisjs-server-stats/log-stream' const service = new LogStreamService('logs/app.log', (entry) => { console.log('New log entry:', entry) }) await service.start() // later... service.stop() ``` -------------------------------- ### GET /__stats/api/filters Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves a list of all saved filters. ```APIDOC ## GET /__stats/api/filters ### Description Returns saved filters. ### Method GET ### Endpoint /__stats/api/filters ### Response #### Success Response (200) - **items** (array) - A list of saved filters. - **id** (integer) - The unique identifier for the filter. - **name** (string) - The name of the filter. - **type** (string) - The type of the filter (e.g., 'queries'). - **filters** (object) - The filter criteria. #### Response Example ```json { "items": [ { "id": 1, "name": "My slow queries", "type": "queries", "filters": { "minDuration": 500 } } ] } ``` ``` -------------------------------- ### Initialize RequestMetrics with custom options Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/trace-and-core.md Instantiate the `RequestMetrics` class with custom configuration for buffer size (`maxRecords`) and rolling window duration (`windowMs`). ```typescript import { RequestMetrics } from 'adonisjs-server-stats' const metrics = new RequestMetrics({ maxRecords: 50_000, windowMs: 30_000, // 30-second window }) ``` -------------------------------- ### GET /__stats/api/jobs/:id Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves the details of a specific job. ```APIDOC ## GET /__stats/api/jobs/:id ### Description Returns job detail. ### Method GET ### Endpoint /__stats/api/jobs/:id ### Parameters #### Path Parameters - **id** (URL) — job ID ### Response #### Success Response (200) - **id** (string) - The job ID. - **name** (string) - The name of the job. - **status** (string) - The status of the job. - **progress** (integer) - The progress of the job (0-100). - **data** (object) - The data associated with the job. - **result** (object) - The result of the job if completed. - **failedReason** (string) - The reason for failure if the job failed. ### Response Example ```json { "id": "job-123", "name": "send-email", "status": "completed", "progress": 100, "data": {}, "result": {}, "failedReason": null } ``` ``` -------------------------------- ### new StatsEngine(collectors: MetricCollector[]) Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/stats-engine.md Initializes a new StatsEngine instance with an array of metric collector instances. ```APIDOC ## new StatsEngine(collectors: MetricCollector[]) ### Description Initializes a new StatsEngine instance with an array of metric collector instances to run each tick. ### Method Signature ```ts new StatsEngine(collectors: MetricCollector[]) ``` ### Parameters - **collectors** (`MetricCollector[]`) - Required - Array of collector instances to run each tick. ### Example ```ts import { StatsEngine } from 'adonisjs-server-stats' import { processCollector, systemCollector, httpCollector, } from 'adonisjs-server-stats/collectors' const engine = new StatsEngine([ processCollector(), systemCollector(), httpCollector(), ]) ``` ``` -------------------------------- ### GET /__stats/api/routes Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves a list of all registered routes in the application. ```APIDOC ## GET /__stats/api/routes ### Description Returns route table. ### Method GET ### Endpoint /__stats/api/routes ### Response #### Success Response (200) - **items** (array) - A list of route objects. - **method** (string) - The HTTP method of the route. - **pattern** (string) - The URL pattern of the route. - **name** (string) - The name of the route. - **handler** (string) - The controller and method handling the route. - **middleware** (array) - An array of middleware applied to the route. ### Response Example ```json { "items": [ { "method": "GET", "pattern": "/users/:id", "name": "users.show", "handler": "UsersController.show", "middleware": ["auth", "throttle:60,1"] } ] } ``` ``` -------------------------------- ### Get Job Queue Overview Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Returns an overview of the job queue, including counts of active, waiting, delayed, and failed jobs, as well as worker information. ```json { "overview": { "active": 2, "waiting": 10, "delayed": 5, "failed": 0, "workerCount": 2 }, "recentJobs": [ { "id": "job-123", "name": "send-email", "status": "completed", "progress": 100 } ] } ``` -------------------------------- ### GET /__stats/api/config Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves the application configuration, with sensitive information redacted. ```APIDOC ## GET /__stats/api/config ### Description Returns app config (secrets redacted). ### Method GET ### Endpoint /__stats/api/config ### Response #### Success Response (200) - **app** (object) - Application level configuration. - **appKey** (string) - The application key (redacted). - **nodeEnv** (string) - The Node.js environment. - **database** (object) - Database configuration. - **postgres** (object) - PostgreSQL specific configuration. - **host** (string) - The database host. - **password** (string) - The database password (redacted). ### Response Example ```json { "app": { "appKey": "***", "nodeEnv": "development" }, "database": { "postgres": { "host": "localhost", "password": "***" } } } ``` ``` -------------------------------- ### GET /__stats/api/cache/:key Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves the details of a specific cache key. ```APIDOC ## GET /__stats/api/cache/:key ### Description Returns cache key detail. ### Method GET ### Endpoint /__stats/api/cache/:key ### Parameters #### Path Parameters - **key** (URL) — cache key name ### Response #### Success Response (200) - **key** (string) - The cache key name. - **type** (string) - The type of the cache key. - **value** (string) - The value of the cache key. - **ttl** (integer) - Time to live in seconds (-1 for no expiry). - **size** (integer) - The size of the cache key in bytes. ### Response Example ```json { "key": "user:123", "type": "string", "value": "{...}", "ttl": -1, "size": 256 } ``` ``` -------------------------------- ### Initialize HTTP Collector with Options Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/collectors.md Tracks HTTP request throughput, response times, and error rates. It can be configured with options like `maxRecords` and `windowMs`. ```typescript import { httpCollector } from 'adonisjs-server-stats/collectors' const collector = httpCollector({ maxRecords: 50_000 }) ``` -------------------------------- ### GET /__stats/api/cache Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves Redis cache statistics and a list of keys. ```APIDOC ## GET /__stats/api/cache ### Description Returns Redis cache stats and key listing. ### Method GET ### Endpoint /__stats/api/cache ### Response #### Success Response (200) - **info** (object) - Redis server information. - **used_memory_mb** (integer) - Used memory in MB. - **connected_clients** (integer) - Number of connected clients. - **keyspace_hits** (integer) - Number of keyspace hits. - **keyspace_misses** (integer) - Number of keyspace misses. - **keys** (array) - A list of cache keys. - **key** (string) - The cache key name. - **type** (string) - The type of the cache key. - **ttl** (integer) - Time to live in seconds (-1 for no expiry). - **size** (integer) - The size of the cache key in bytes. ### Response Example ```json { "info": { "used_memory_mb": 42, "connected_clients": 3, "keyspace_hits": 1500, "keyspace_misses": 100 }, "keys": [ { "key": "user:123", "type": "string", "ttl": -1, "size": 256 } ] } ``` ``` -------------------------------- ### GET /__stats/api/emails/:id/preview Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves the HTML preview for a specific email. ```APIDOC ## GET /__stats/api/emails/:id/preview ### Description Returns email HTML preview. ### Method GET ### Endpoint /__stats/api/emails/:id/preview ### Parameters #### Path Parameters - **id** (URL) — email ID ### Response #### Success Response (200) - Raw HTML for iframe embedding. ``` -------------------------------- ### GET /__stats/api/emails Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves a paginated list of emails sent by the application. ```APIDOC ## GET /__stats/api/emails ### Description Returns paginated email list. ### Method GET ### Endpoint /__stats/api/emails ### Response #### Success Response (200) - **items** (array) - A list of email objects. - **id** (integer) - The email ID. - **from** (string) - The sender's email address. - **to** (string) - The recipient's email address. - **subject** (string) - The subject of the email. - **status** (string) - The status of the email (e.g., 'sent'). - **timestamp** (integer) - The Unix timestamp when the email was sent. - **total** (integer) - The total number of emails. - **page** (integer) - The current page number. - **perPage** (integer) - The number of items per page. - **lastPage** (integer) - The last page number. ### Response Example ```json { "items": [ { "id": 1, "from": "noreply@example.com", "to": "user@example.com", "subject": "Welcome", "status": "sent", "timestamp": 1700000000000 } ], "total": 500, "page": 1, "perPage": 50, "lastPage": 10 } ``` ``` -------------------------------- ### GET /__stats/api/queries Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves a paginated list of all executed database queries. ```APIDOC ## GET /__stats/api/queries ### Description Returns paginated query list. ### Method GET ### Endpoint /__stats/api/queries ### Parameters #### Query Parameters - **page** (integer) - Optional - page number, defaults to 1 - **limit** (integer) - Optional - queries per page, defaults to 50 ### Response #### Success Response (200) - **items** (array) - List of query objects. - **total** (integer) - Total number of queries. - **page** (integer) - Current page number. - **perPage** (integer) - Number of queries per page. - **lastPage** (integer) - The last page number. ### Response Example ```json { "items": [ { "id": 1, "sql": "SELECT...", "duration": 45, "timestamp": 1700000000000 } ], "total": 5000, "page": 1, "perPage": 50, "lastPage": 100 } ``` **Status Codes:** `200`, `403` ``` -------------------------------- ### GET /__stats/api/traces/:id Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves the details of a specific trace, including all its spans. ```APIDOC ## GET /__stats/api/traces/:id ### Description Returns trace detail with spans. ### Method GET ### Endpoint /__stats/api/traces/:id ### Parameters #### Path Parameters - **id** (URL) — trace ID ### Response #### Success Response (200) - **id** (integer) - The trace ID. - **method** (string) - The HTTP method of the request. - **url** (string) - The URL of the request. - **statusCode** (integer) - The HTTP status code of the response. - **totalDuration** (integer) - The total duration of the trace in milliseconds. - **spans** (array) - An array containing all spans for this trace. - **timestamp** (integer) - The Unix timestamp when the trace occurred. ### Response Example ```json { "id": 1, "method": "GET", "url": "/users", "statusCode": 200, "totalDuration": 125, "spans": [ /* all spans */ ], "timestamp": 1700000000000 } ``` ``` -------------------------------- ### GET /__stats/api/events Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves a paginated list of events that have occurred within the application. ```APIDOC ## GET /__stats/api/events ### Description Returns paginated event list. ### Method GET ### Endpoint /__stats/api/events ### Response #### Success Response (200) - **items** (array) - A list of event objects. - **id** (integer) - The event ID. - **event** (string) - The name of the event. - **data** (string) - JSON string representing event data. - **timestamp** (integer) - The Unix timestamp when the event occurred. - **total** (integer) - The total number of events. - **page** (integer) - The current page number. - **perPage** (integer) - The number of items per page. - **lastPage** (integer) - The last page number. ### Response Example ```json { "items": [ { "id": 1, "event": "user:registered", "data": "{}", "timestamp": 1700000000000 } ], "total": 500, "page": 1, "perPage": 50, "lastPage": 10 } ``` ``` -------------------------------- ### Custom Collector Pattern Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/api-reference/collectors.md Demonstrates how to implement the `MetricCollector` interface to create custom collectors for specific monitoring needs, such as disk space. ```APIDOC ## Custom Collector Pattern Implement the `MetricCollector` interface to create your own collectors. ### Example: Disk Collector ```ts import type { MetricCollector } from 'adonisjs-server-stats' function diskCollector(): MetricCollector { return { name: 'disk', label: 'disk — capacity monitoring', getConfig() { return {} }, async collect() { const { availableSpace, totalSpace } = await getDiskInfo() // Assuming getDiskInfo is defined elsewhere return { diskAvailableGb: availableSpace / 1e9, diskTotalGb: totalSpace / 1e9, diskUsagePercent: ((totalSpace - availableSpace) / totalSpace) * 100, } }, } } // Configuration in config/server_stats.ts: import { defineConfig } from 'adonisjs-server-stats' import { processCollector } from 'adonisjs-server-stats/collectors' export default defineConfig({ collectors: [ processCollector(), diskCollector(), // Mix with built-in collectors ], }) ``` ``` -------------------------------- ### Add to .gitignore Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/README.md Add the dashboard's SQLite database path to your `.gitignore` file to prevent it from being committed to version control. ```ignore .adonisjs/server-stats/ ``` -------------------------------- ### GET /__stats/api/logs Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves paginated log entries, with optional filtering by log level. ```APIDOC ## GET /__stats/api/logs ### Description Returns paginated log entries. ### Method GET ### Endpoint /__stats/api/logs ### Parameters #### Query Parameters - **page** (integer) - Optional, default 1. The page number for pagination. - **level** (string) - Optional. Filter logs by this level (e.g., 'error', 'info'). ### Response #### Success Response (200) - **items** (array) - A list of log entry objects. - **level** (string) - The log level. - **message** (string) - The log message. - **context** (object) - Additional context for the log entry. - **timestamp** (integer) - The Unix timestamp when the log was recorded. - **total** (integer) - The total number of log entries. - **page** (integer) - The current page number. - **perPage** (integer) - The number of items per page. - **lastPage** (integer) - The last page number. ### Response Example ```json { "items": [ { "level": "error", "message": "Something went wrong", "context": {}, "timestamp": 1700000000000 } ], "total": 2000, "page": 1, "perPage": 50, "lastPage": 40 } ``` ``` -------------------------------- ### GET /admin/api/debug/diagnostics Source: https://github.com/simulieren/adonisjs-server-stats/blob/main/_autodocs/endpoints.md Retrieves diagnostics information for various providers and checks the health of collectors. ```APIDOC ## GET /admin/api/debug/diagnostics ### Description Returns provider diagnostics and collector health. ### Method GET ### Endpoint /admin/api/debug/diagnostics ### Response #### Success Response (200) - **collectors** (array) - List of collector objects, each with name, label, status, lastError, and lastErrorAt. - **features** (object) - An object indicating the status of various application features. ### Response Example ```json { "collectors": [ { "name": "process", "label": "process — cpu, memory, event loop, uptime", "status": "healthy", "lastError": null, "lastErrorAt": null }, { "name": "http", "label": "http — buffer: 10,000, window: 60s", "status": "healthy", "lastError": null, "lastErrorAt": null } ], "features": { "lucid": true, "redis": true, "bullmq": true, "transmit": true, "betterSqlite3": true } } ``` **Status Codes:** `200`, `403` ```