feat(logging): add real-time log streaming via websocket

- Implement WebSocket endpoint for streaming logs to clients
- Add log broadcaster to manage client connections and history
- Update documentation with new WebSocket API details
- Include gorilla/websocket dependency for WebSocket support
This commit is contained in:
2026-03-17 19:12:15 +08:00
parent 20ec25328d
commit 33e5119b0a
9 changed files with 444 additions and 150 deletions
+115
View File
@@ -713,6 +713,90 @@ X-Timestamp: 1704067200000
---
## Real-time Log Streaming (WebSocket)
**Endpoint:** `/logs`
**Protocol:** WebSocket
**Auth Required:** No (but requires authentication token in URL query parameter)
**Permission Level:** None
Establish a WebSocket connection to receive real-time log streaming from the server.
### Connection
Connect to `ws://localhost:8080/system/getLogs` (or `wss://` for secure connection).
**Query Parameters:**
- `token`: Authentication token (optional, for tracking which user is viewing logs)
**Example:**
```
ws://localhost:8080/logs?token=your_token_here
```
### Message Format
Logs are sent as JSON messages with the following structure:
```json
{
"level": 1,
"content": "Log message content",
"timestamp": "2024-01-01 12:00:00.000"
}
```
| Field | Type | Description |
|-------|------|-------------|
| level | int | Log level: 0=DEBUG, 1=INFO, 2=WARNING, 3=ERROR, 4=FATAL |
| content | string | Log message content |
| timestamp | string | Log timestamp (YYYY-MM-DD HH:MM:SS.mmm format) |
### Log Levels
| Level | Name | Description |
|-------|------|-------------|
| 0 | DEBUG | Debug messages (only visible when debug mode is enabled) |
| 1 | INFO | Informational messages |
| 2 | WARNING | Warning messages |
| 3 | ERROR | Error messages |
| 4 | FATAL | Fatal/critical messages |
### Behavior
1. **On Connection**: The server immediately sends the last 100 log entries
2. **Streaming**: All new log entries are pushed in real-time to all connected clients
3. **Multi-client**: Multiple clients can connect simultaneously and receive the same log stream
4. **History**: Only the most recent 100 log entries are kept in memory
### Example Usage (JavaScript)
```javascript
const socket = new WebSocket('ws://localhost:8080/logs?token=your_token');
socket.onopen = () => {
console.log('Connected to log server');
};
socket.onmessage = (event) => {
const log = JSON.parse(event.data);
console.log(`[${log.timestamp}] ${log.content}`);
// Log level example
const levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'FATAL'];
console.log(`[${levels[log.level]}] ${log.content}`);
};
socket.onclose = () => {
console.log('Disconnected from log server');
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
};
```
---
## User Permissions
| Permission | superuser | admin | visitor |
@@ -723,11 +807,16 @@ X-Timestamp: 1704067200000
| List instances | ✓ | ✓ | ✓ (limited) |
| Manage users | ✓ | ✗ | ✗ |
| List active sessions | ✓ | ✓ | ✗ |
| View logs | ✓ | ✓ | ✓ |
---
## Timestamp Validation
All requests include a `timeStamp` field (Unix timestamp in milliseconds). The server validates that the timestamp is within ±3000ms of the server time. This prevents replay attacks.
---
## Password Requirements
Passwords must meet the following complexity requirements:
@@ -737,10 +826,14 @@ Passwords must meet the following complexity requirements:
- At least one digit (0-9)
- At least one special character (!@#$%^&*()_+-=[]{}|;:,.<>?)
---
## Token
Tokens are valid for 1 hour. After expiration, users need to re-login to get a new token.
---
## Generated Config Files
Instance configuration files are saved in the specified `instancePath` with the naming convention:
@@ -749,3 +842,25 @@ superfrpc_<username>_<instanceName>.toml
```
Example: `superfrpc_admin_my_frpc.toml`
---
## Error Codes
| Code | Message | Description |
|------|---------|-------------|
| 400 | Bad Request | Invalid request parameters |
| 401 | Unauthorized | Missing or invalid authentication token |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource not found |
| 500 | Internal Server Error | Server internal error |
---
## Rate Limiting
The API implements rate limiting to prevent abuse:
- Login attempts: Maximum 5 attempts per minute per IP
- All other endpoints: 100 requests per minute per token
Exceeding rate limits will result in temporary IP or token blocking.