rn-kore-bot-socket-lib-v77
Version:
Description of Bot Scocket SDK library
273 lines (215 loc) • 8.15 kB
Markdown
The Bot SDK now includes comprehensive logging for all important API calls and WebSocket events. This guide explains how to use the logging features.
- **Structured Logging**: All logs include timestamps, categories, and structured data
- **Multiple Log Levels**: DEBUG, INFO, WARN, ERROR
- **API Call Tracking**: Request/response logging with timing
- **WebSocket Events**: Connection, message, and error logging
- **In-Memory Storage**: Access logs programmatically for debugging
- **Configurable**: Set log levels to control verbosity
- **Enable/Disable Flag**: Completely enable or disable all logging output
```typescript
import KoreBotClient, { Logger, LogLevel } from 'rn-socketlib-test';
// Method 1: Control logging through BotClient (Recommended)
const botClient = KoreBotClient.getInstance();
// Enable/disable logging via BotClient
botClient.enableLogger(); // Enable all logging
botClient.disableLogger(); // Disable all logging completely
// Check logging status via BotClient
console.log('Logging enabled:', botClient.isLoggerEnabled());
// Method 2: Direct Logger control (Alternative)
Logger.enableLogging(); // Enable all logging
// Logger.disableLogging(); // Disable all logging completely
// Set log level (optional - defaults to INFO)
Logger.setLogLevel(LogLevel.DEBUG); // Show all logs
// Logger.setLogLevel(LogLevel.ERROR); // Show only errors
// Initialize your bot client
const botConfig = {
botName: 'MyBot',
botId: 'your-bot-id',
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
botUrl: 'https://your-bot-url.com',
identity: 'user@example.com',
jwtServerUrl: 'https://your-jwt-server.com/',
isWebHook: false,
value_aud: 'your-audience',
isHeaderVisible: true,
isFooterVisible: true
};
const botClient = KoreBotClient.getInstance();
botClient.initializeBotClient(botConfig);
```
```
[] [INFO] [API_REQUEST] POST https://bot-url/users/sts
[] [INFO] [API_SUCCESS] POST https://bot-url/users/sts - Success (150ms)
[] [ERROR] [API_ERROR] POST https://bot-url/users/sts - Error (200ms)
```
```
[] [INFO] [WEBSOCKET] WebSocket Connected
[] [INFO] [WEBSOCKET] WebSocket Message Received
[] [ERROR] [WEBSOCKET_ERROR] WebSocket Error
```
```
[] [INFO] [CONNECTION] JWT Token Authorization Started
[] [INFO] [CONNECTION] Bot Disconnect Called
[] [ERROR] [CONNECTION_ERROR] Maximum Reconnection Limit Reached
```
The Logger provides a global flag to completely enable or disable all logging functionality:
**Method 1: Through BotClient (Recommended)**
```typescript
import KoreBotClient from 'rn-socketlib-test';
const botClient = KoreBotClient.getInstance();
// Disable all logging (no console output, no log storage)
botClient.disableLogger();
// Enable logging again
botClient.enableLogger();
// Check current status
if (botClient.isLoggerEnabled()) {
console.log('Logging is currently enabled');
} else {
console.log('Logging is currently disabled');
}
```
**Method 2: Direct Logger Control**
```typescript
import { Logger } from 'rn-socketlib-test';
// Disable all logging (no console output, no log storage)
Logger.disableLogging();
// Enable logging again
Logger.enableLogging();
// Check current status
if (Logger.isLoggingEnabledFlag()) {
console.log('Logging is currently enabled');
} else {
console.log('Logging is currently disabled');
}
```
**Production Builds**: Disable logging to improve performance and reduce console noise
```typescript
// In your app initialization - using BotClient
const botClient = KoreBotClient.getInstance();
if (__DEV__) {
botClient.enableLogger();
Logger.setLogLevel(LogLevel.DEBUG);
} else {
botClient.disableLogger(); // No logging in production
}
```
**Conditional Debugging**: Enable logging only when needed
```typescript
// Enable logging for specific debugging sessions - using BotClient
const botClient = KoreBotClient.getInstance();
const enableDebugLogging = false; // Set to true when debugging
if (enableDebugLogging) {
botClient.enableLogger();
Logger.setLogLevel(LogLevel.DEBUG);
} else {
botClient.disableLogger();
}
```
**Runtime Toggle**: Enable/disable logging during app runtime
```typescript
// Toggle logging based on user action or app state
const botClient = KoreBotClient.getInstance();
// In response to user action
const handleToggleLogging = () => {
if (botClient.isLoggerEnabled()) {
botClient.disableLogger();
console.log('Logging disabled');
} else {
botClient.enableLogger();
console.log('Logging enabled');
}
};
```
**Note**: When logging is disabled, no logs are written to console or stored in memory, providing optimal performance.
```typescript
import { Logger, LogLevel } from 'rn-socketlib-test';
// Get all logs
const allLogs = Logger.getLogs();
// Get only error logs
const errorLogs = Logger.getLogs(LogLevel.ERROR);
// Clear logs
Logger.clearLogs();
```
```typescript
interface LogEntry {
timestamp: string; // ISO timestamp
level: LogLevel; // DEBUG, INFO, WARN, ERROR
category: string; // API_REQUEST, WEBSOCKET, CONNECTION, etc.
message: string; // Human readable message
data?: any; // Structured data (request params, response data, etc.)
error?: any; // Error object if applicable
}
```
| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/users/sts` | POST | JWT Token Generation |
| `/api/oAuth/token/jwtgrant` | POST | JWT Token Authorization |
| `/api/rtm/start` | POST | RTM URL Retrieval |
| `/api/botmessages/rtm` | GET | Bot History |
| `/api/websdkthemes/{botId}/activetheme` | GET | Theme API |
| `searchassistapi/.../getresultviewsettings` | GET | Search Settings |
| WebSocket Connection | - | Real-time messaging |
```typescript
// Listen for connection events
const connectionLogs = Logger.getLogs().filter(log =>
log.category.includes('CONNECTION')
);
console.log('Connection Events:', connectionLogs);
```
```typescript
// Find failed API calls
const apiErrors = Logger.getLogs(LogLevel.ERROR).filter(log =>
log.category === 'API_ERROR'
);
apiErrors.forEach(error => {
console.log(`API Error: ${error.message}`, error.data);
});
```
```typescript
// Monitor WebSocket messages
const wsLogs = Logger.getLogs().filter(log =>
log.category === 'WEBSOCKET'
);
console.log('WebSocket Activity:', wsLogs);
```
```typescript
// Get logs as JSON for support tickets
const logsForSupport = JSON.stringify(Logger.getLogs(), null, 2);
console.log('Support Logs:', logsForSupport);
```
- **DEBUG**: Detailed information, typically only of interest when diagnosing problems
- **INFO**: General information about what the program is doing
- **WARN**: Something unexpected happened, but the software is still working
- **ERROR**: Due to a more serious problem, the software has not been able to perform some function
- Logging is optimized for minimal performance impact
- Logs are stored in memory with automatic rotation (max 1000 entries)
- Log levels can be adjusted to reduce verbosity in production
- Structured data is logged without sensitive information (tokens are masked)
## Best Practices
1. **Development**: Use `LogLevel.DEBUG` for detailed troubleshooting
2. **Production**: Use `LogLevel.WARN` or `LogLevel.ERROR` to minimize noise
3. **Support**: Export logs using `Logger.getLogs()` for support tickets
4. **Monitoring**: Regularly check error logs for recurring issues
5. **Memory Management**: Call `Logger.clearLogs()` periodically in long-running apps