diff --git a/docs/API_DOCUMENTATION.md b/docs/API_DOCUMENTATION.md deleted file mode 100644 index 3b3368e..0000000 --- a/docs/API_DOCUMENTATION.md +++ /dev/null @@ -1,765 +0,0 @@ -# RDK Logger API Documentation - -## Table of Contents -1. [Overview](#overview) -2. [Architecture](#architecture) -3. [Installation & Build](#installation--build) -4. [Quick Start](#quick-start) -5. [Core APIs](#core-apis) -6. [Configuration](#configuration) -7. [Runtime Control](#runtime-control) -8. [Log Levels](#log-levels) -9. [Utilities](#utilities) -10. [Examples](#examples) -11. [Error Handling](#error-handling) -12. [Best Practices](#best-practices) - -## Overview - -RDK Logger is a comprehensive logging framework designed for RDK (Reference Design Kit) components. It provides: - -- **Centralized Configuration**: Single `debug.ini` file for all components -- **Runtime Control**: Dynamic log level changes without restart -- **Multi-level Logging**: Support for FATAL, ERROR, WARN, NOTICE, INFO, DEBUG, TRACE -- **Module-specific Control**: Independent log levels per component/module -- **Performance Optimized**: Minimal overhead when logging is disabled -- **Thread-safe**: Safe for multi-threaded applications - -## Architecture - -``` -┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐ -│ Application │───▶│ RDK Logger │───▶│ Log Output │ -│ │ │ │ │ (stdout/file) │ -└─────────────────┘ └──────────────────┘ └─────────────────┘ - │ - ▼ - ┌──────────────────┐ - │ debug.ini │ - │ Configuration │ - └──────────────────┘ -``` - -The RDK Logger sits between your application and the actual log output, providing filtering, formatting, and runtime control capabilities. - -## Installation & Build - -### Prerequisites -- `liblog4c` - Log4C logging library -- `libglib-2.0` - GLib library -- `autotools` - For building from source - -### Build Instructions -```bash -# Configure and build -./configure -make - -# Install -sudo make install -``` - -### Linking in Your Project -```bash -# Compile flags -gcc -o myapp myapp.c -lrdkloggers -llog4c -lglib-2.0 -``` - -## Quick Start - -### 1. Include Headers -```c -#include "rdk_logger.h" -``` - -### 2. Initialize Logger -```c -int main() { - // Initialize with default config file (/etc/debug.ini) - if (RDK_LOGGER_INIT() != RDK_SUCCESS) { - fprintf(stderr, "Failed to initialize RDK Logger\n"); - return -1; - } - - // Your application code here - - // Clean up - rdk_logger_deinit(); - return 0; -} -``` - -### 3. Log Messages -```c -// Basic logging -RDK_LOG(RDK_LOG_INFO, "LOG.RDK.MYAPP", "Application started successfully\n"); - -// Formatted logging -int port = 8080; -RDK_LOG(RDK_LOG_NOTICE, "LOG.RDK.MYAPP", "Server listening on port %d\n", port); - -// Error logging -RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.MYAPP", "Failed to connect to database: %s\n", strerror(errno)); -``` - -## Core APIs - -### Initialization Functions - -#### `rdk_logger_init()` -```c -rdk_Error rdk_logger_init(const char* debugConfigFile); -``` -**Purpose**: Initialize the RDK Logger with a specific configuration file. - -**Parameters**: -- `debugConfigFile`: Path to the debug.ini configuration file - -**Returns**: `RDK_SUCCESS` on success, error code otherwise - -**Example**: -```c -rdk_Error ret = rdk_logger_init("/etc/debug.ini"); -if (ret != RDK_SUCCESS) { - printf("Logger initialization failed\n"); -} -``` - -#### `rdk_logger_ext_init()` -```c -rdk_Error rdk_logger_ext_init(const rdk_logger_ext_config_t* config); -``` -**Purpose**: Extended initialization with custom log file configuration. - -**Parameters**: -- `config`: Pointer to extended configuration structure - -**Configuration Structure**: -```c -typedef struct rdk_logger_ext_config_t { - char fileName[RDK_LOGGER_EXT_FILENAME_SIZE]; // Log file name - char logdir[RDK_LOGGER_EXT_LOGDIR_SIZE]; // Log directory path - long maxSize; // Max file size in bytes - long maxCount; // Max number of log files -} rdk_logger_ext_config_t; -``` - -**Example**: -```c -rdk_logger_ext_config_t config = { - .fileName = "myapp.log", - .logdir = "/var/log/", - .maxSize = 1024 * 1024, // 1MB - .maxCount = 5 // Keep 5 log files -}; -rdk_logger_ext_init(&config); -``` - -#### `rdk_logger_deinit()` -```c -rdk_Error rdk_logger_deinit(void); -``` -**Purpose**: Clean up and deinitialize the logger. - -**Returns**: `RDK_SUCCESS` on success - -### Logging Functions - -#### `RDK_LOG` Macro -```c -#define RDK_LOG rdk_logger_msg_printf -``` -**Purpose**: Primary logging macro for formatted messages. - -**Syntax**: -```c -RDK_LOG(level, module, format, ...); -``` - -**Parameters**: -- `level`: Log level (see [Log Levels](#log-levels)) -- `module`: Module name string (should match debug.ini entries) -- `format`: Printf-style format string -- `...`: Variable arguments for format string - -#### `rdk_logger_msg_printf()` -```c -void rdk_logger_msg_printf(rdk_LogLevel level, const char *module, const char *format, ...); -``` -**Purpose**: Core logging function with printf-style formatting. - -**Example**: -```c -rdk_logger_msg_printf(RDK_LOG_DEBUG, "LOG.RDK.NETWORK", - "Connection established to %s:%d\n", hostname, port); -``` - -#### `rdk_logger_msg_vsprintf()` -```c -void rdk_logger_msg_vsprintf(rdk_LogLevel level, const char *module, const char *format, va_list args); -``` -**Purpose**: Logging function that accepts a `va_list` for wrapper functions. - -**Example**: -```c -void my_log_wrapper(rdk_LogLevel level, const char *module, const char *format, ...) { - va_list args; - va_start(args, format); - rdk_logger_msg_vsprintf(level, module, format, args); - va_end(args); -} -``` - -### Query and Control Functions - -#### `rdk_logger_is_logLevel_enabled()` -```c -rdk_logger_Bool rdk_logger_is_logLevel_enabled(const char *module, rdk_LogLevel level); -``` -**Purpose**: Check if a specific log level is enabled for a module. - -**Returns**: `TRUE` if enabled, `FALSE` otherwise - -**Example**: -```c -if (rdk_logger_is_logLevel_enabled("LOG.RDK.MYAPP", RDK_LOG_DEBUG)) { - // Expensive debug computation only if debug logging is enabled - char *debug_info = generate_debug_info(); - RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.MYAPP", "Debug info: %s\n", debug_info); - free(debug_info); -} -``` - -#### `rdk_logger_enable_logLevel()` -```c -rdk_logger_Bool rdk_logger_enable_logLevel(const char *module, rdk_LogLevel logLevel, rdk_logger_Bool enableLogLvl); -``` -**Purpose**: Dynamically enable or disable a log level for a module at runtime. - -**Parameters**: -- `module`: Module name -- `logLevel`: Log level to modify -- `enableLogLvl`: `TRUE` to enable, `FALSE` to disable - -**Returns**: `TRUE` if successful - -**Example**: -```c -// Enable debug logging temporarily -rdk_logger_enable_logLevel("LOG.RDK.MYAPP", RDK_LOG_DEBUG, TRUE); - -// ... debug operations ... - -// Disable debug logging -rdk_logger_enable_logLevel("LOG.RDK.MYAPP", RDK_LOG_DEBUG, FALSE); -``` - -### Utility Functions - -#### `rdk_logger_level_from_string()` -```c -rdk_LogLevel rdk_logger_level_from_string(const char* level); -``` -**Purpose**: Convert string representation to log level enum. - -**Parameters**: -- `level`: String like "INFO", "DEBUG", "ERROR" - -**Returns**: Corresponding `rdk_LogLevel` value, or `RDK_LOG_NONE` if invalid - -**Example**: -```c -rdk_LogLevel level = rdk_logger_level_from_string("DEBUG"); -if (level != RDK_LOG_NONE) { - rdk_logger_enable_logLevel("LOG.RDK.MYAPP", level, TRUE); -} -``` - -#### `rdk_logger_log_onboard()` -```c -void rdk_logger_log_onboard(const char *module, const char *msg, ...); -``` -**Purpose**: Special logging function for onboard/milestone logging. - -**Example**: -```c -rdk_logger_log_onboard("LOG.RDK.SYSTEM", "System initialization completed"); -``` - -## Configuration - -### debug.ini File Format - -The `debug.ini` file controls logging behavior for all modules: - -```ini -########################################################################## -# RDK Logger Configuration -# Format: LOG.RDK.= -########################################################################## - -# Default log level for all modules -LOG.RDK.DEFAULT=WARNING - -# Module-specific log levels -LOG.RDK.NETWORK=DEBUG # Network module: debug and above -LOG.RDK.DATABASE=INFO # Database module: info and above -LOG.RDK.SECURITY=ERROR # Security module: error and above -LOG.RDK.TESTMODULE=NONE # Test module: no logging -``` - -### Configuration Locations - -1. **Primary**: `/etc/debug.ini` -2. **Override**: `/nvram/debug.ini` (takes precedence if exists) -3. **Custom**: Specified in `rdk_logger_init()` call - -### Module Naming Convention - -- **RDK Components**: Must start with `LOG.RDK.` -- **Example**: `LOG.RDK.NETWORK`, `LOG.RDK.AUDIO`, `LOG.RDK.VIDEO` -- **Default Module**: `LOG.RDK.DEFAULT` sets the fallback level - -## Runtime Control - -### Using rdklogctrl Utility - -The `rdklogctrl` command-line utility allows runtime modification of log levels: - -```bash -# Set log level for a module -rdklogctrl - -# Examples -rdklogctrl myapp LOG.RDK.NETWORK DEBUG -rdklogctrl receiver LOG.RDK.AUDIO INFO -rdklogctrl player LOG.RDK.VIDEO ERROR - -# Disable specific log level (using ~ prefix) -rdklogctrl myapp LOG.RDK.NETWORK ~DEBUG -``` - -**Parameters**: -- `app_name`: Process name as shown by `ps` command -- `module_name`: Module name (must match debug.ini format) -- `log_level`: FATAL, ERROR, WARN, NOTICE, INFO, DEBUG, TRACE, NONE - -### Programmatic Runtime Control - -```c -// Enable debug logging at runtime -rdk_logger_enable_logLevel("LOG.RDK.MYAPP", RDK_LOG_DEBUG, TRUE); - -// Check if logging is enabled before expensive operations -if (rdk_dbg_enabled("LOG.RDK.MYAPP", RDK_LOG_TRACE)) { - generate_detailed_trace(); -} -``` - -## Log Levels - -### Available Log Levels - -| Level | Value | Description | Use Case | -|-------|-------|-------------|----------| -| `RDK_LOG_FATAL` | 0 | System unusable | Critical failures, system crash | -| `RDK_LOG_ERROR` | 1 | Error conditions | Errors that affect functionality | -| `RDK_LOG_WARN` | 2 | Warning conditions | Potential problems, degraded performance | -| `RDK_LOG_NOTICE` | 3 | Normal significant condition | Important normal events | -| `RDK_LOG_INFO` | 4 | Informational messages | General application flow | -| `RDK_LOG_DEBUG` | 5 | Debug-level messages | Detailed debugging information | -| `RDK_LOG_TRACE` | 6 | Trace-level messages | Very detailed execution tracing | -| `RDK_LOG_NONE` | 7 | No logging | Disable all logging | - -### Log Level Hierarchy - -Setting a log level enables that level and all higher priority levels: - -``` -TRACE → DEBUG → INFO → NOTICE → WARN → ERROR → FATAL -``` - -**Example**: Setting `DEBUG` enables DEBUG, INFO, NOTICE, WARN, ERROR, and FATAL messages. - -### Legacy Compatibility - -For backward compatibility with legacy RDK components: - -```c -#define RDK_LOG_TRACE1 RDK_LOG_TRACE -#define RDK_LOG_TRACE2 RDK_LOG_TRACE -// ... up to RDK_LOG_TRACE9 -``` - -## Utilities - -### rdklogctrl - Runtime Log Control - -**Location**: `utils/rdklogctrl` - -**Purpose**: Command-line utility for modifying log levels of running processes. - -**Usage**: -```bash -rdklogctrl -``` - -**Examples**: -```bash -# Enable debug logging for network module -rdklogctrl receiver LOG.RDK.NETWORK DEBUG - -# Disable all logging for test module -rdklogctrl myapp LOG.RDK.TEST NONE - -# Turn off only error logs (keep others) -rdklogctrl player LOG.RDK.AUDIO ~ERROR -``` - -### rdklogmilestone - Milestone Utility - -**Location**: `utils/rdklogmilestone.c` - -**Purpose**: C utility for milestone logging from applications. - -**Usage**: -```bash -rdklogmilestone "APPLICATION_READY" -``` - -## Examples - -### Basic Application Integration - -```c -#include -#include -#include "rdk_logger.h" - -#define MODULE_NAME "LOG.RDK.MYAPP" - -int main() { - // Initialize logger - if (RDK_LOGGER_INIT() != RDK_SUCCESS) { - fprintf(stderr, "Failed to initialize RDK Logger\n"); - return EXIT_FAILURE; - } - - // Log application startup - RDK_LOG(RDK_LOG_NOTICE, MODULE_NAME, "Application starting up\n"); - - // Example operations with different log levels - RDK_LOG(RDK_LOG_INFO, MODULE_NAME, "Initializing components\n"); - - // Conditional debug logging for performance - if (rdk_dbg_enabled(MODULE_NAME, RDK_LOG_DEBUG)) { - RDK_LOG(RDK_LOG_DEBUG, MODULE_NAME, "Debug mode enabled\n"); - } - - // Simulated error condition - int error_code = 42; - if (error_code != 0) { - RDK_LOG(RDK_LOG_ERROR, MODULE_NAME, - "Operation failed with error code %d\n", error_code); - } - - // Log application shutdown - RDK_LOG(RDK_LOG_NOTICE, MODULE_NAME, "Application shutting down\n"); - - rdk_logger_deinit(); - return EXIT_SUCCESS; -} -``` - -### Network Service Example - -```c -#include "rdk_logger.h" -#include -#include - -#define NET_MODULE "LOG.RDK.NETWORK" - -int start_server(int port) { - int server_fd; - struct sockaddr_in address; - - RDK_LOG(RDK_LOG_INFO, NET_MODULE, "Starting server on port %d\n", port); - - server_fd = socket(AF_INET, SOCK_STREAM, 0); - if (server_fd < 0) { - RDK_LOG(RDK_LOG_ERROR, NET_MODULE, - "Failed to create socket: %s\n", strerror(errno)); - return -1; - } - - address.sin_family = AF_INET; - address.sin_addr.s_addr = INADDR_ANY; - address.sin_port = htons(port); - - if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { - RDK_LOG(RDK_LOG_ERROR, NET_MODULE, - "Failed to bind to port %d: %s\n", port, strerror(errno)); - close(server_fd); - return -1; - } - - if (listen(server_fd, 10) < 0) { - RDK_LOG(RDK_LOG_ERROR, NET_MODULE, - "Failed to listen on socket: %s\n", strerror(errno)); - close(server_fd); - return -1; - } - - RDK_LOG(RDK_LOG_NOTICE, NET_MODULE, - "Server successfully started and listening on port %d\n", port); - - return server_fd; -} - -void handle_client(int client_fd, struct sockaddr_in *client_addr) { - char client_ip[INET_ADDRSTRLEN]; - inet_ntop(AF_INET, &client_addr->sin_addr, client_ip, INET_ADDRSTRLEN); - - RDK_LOG(RDK_LOG_INFO, NET_MODULE, - "New client connected from %s:%d\n", - client_ip, ntohs(client_addr->sin_port)); - - // Handle client communication... - - RDK_LOG(RDK_LOG_DEBUG, NET_MODULE, - "Processing request from %s\n", client_ip); - - // When done - RDK_LOG(RDK_LOG_INFO, NET_MODULE, - "Client %s disconnected\n", client_ip); - close(client_fd); -} -``` - -### Configuration File Example - -Create `/etc/debug.ini`: -```ini -########################################################################## -# Production Configuration -########################################################################## - -# Default level - only warnings and errors -LOG.RDK.DEFAULT=WARN - -# Network debugging enabled -LOG.RDK.NETWORK=DEBUG - -# Application flow information -LOG.RDK.MYAPP=INFO - -# Security - errors only -LOG.RDK.SECURITY=ERROR - -# Disable test modules in production -LOG.RDK.TEST=NONE -LOG.RDK.UNITTEST=NONE - -# Media components -LOG.RDK.AUDIO=NOTICE -LOG.RDK.VIDEO=NOTICE -``` - -### Wrapper Function Example - -```c -#include "rdk_logger.h" -#include - -// Custom logging wrapper with timestamp -void my_log(rdk_LogLevel level, const char *module, const char *function, - int line, const char *format, ...) { - if (!rdk_dbg_enabled(module, level)) { - return; // Early return if logging disabled - } - - va_list args; - va_start(args, format); - - // Create enhanced format with function and line info - char enhanced_format[512]; - snprintf(enhanced_format, sizeof(enhanced_format), - "[%s:%d] %s", function, line, format); - - rdk_logger_msg_vsprintf(level, module, enhanced_format, args); - va_end(args); -} - -// Convenience macro -#define MY_LOG(level, module, format, ...) \ - my_log(level, module, __FUNCTION__, __LINE__, format, ##__VA_ARGS__) - -// Usage -int main() { - RDK_LOGGER_INIT(); - - MY_LOG(RDK_LOG_INFO, "LOG.RDK.MYAPP", "Application started\n"); - MY_LOG(RDK_LOG_DEBUG, "LOG.RDK.MYAPP", "Variable value: %d\n", 42); - - rdk_logger_deinit(); - return 0; -} -``` - -## Error Handling - -### Return Codes - -All initialization functions return `rdk_Error` type: - -```c -typedef uint32_t rdk_Error; -#define RDK_SUCCESS 0 -``` - -**Common Error Scenarios**: -- Configuration file not found -- Invalid configuration format -- Memory allocation failures -- Log4C initialization errors - -### Error Handling Pattern - -```c -rdk_Error init_logging(const char *config_file) { - rdk_Error ret = rdk_logger_init(config_file); - if (ret != RDK_SUCCESS) { - fprintf(stderr, "Logger initialization failed: %u\n", ret); - fprintf(stderr, "Falling back to stdout logging\n"); - // Implement fallback logging mechanism - return ret; - } - return RDK_SUCCESS; -} -``` - -### Graceful Degradation - -```c -int main() { - // Try to initialize logger - if (RDK_LOGGER_INIT() != RDK_SUCCESS) { - fprintf(stderr, "Warning: RDK Logger initialization failed\n"); - fprintf(stderr, "Continuing with fprintf logging\n"); - - // Application can continue with basic printf/fprintf - printf("Application started (no RDK logging)\n"); - } else { - RDK_LOG(RDK_LOG_NOTICE, "LOG.RDK.MYAPP", "Application started\n"); - } - - // Rest of application... - - return 0; -} -``` - -## Best Practices - -### 1. Module Naming -```c -// Good - descriptive and consistent -#define AUDIO_MODULE "LOG.RDK.AUDIO" -#define NETWORK_MODULE "LOG.RDK.NETWORK" -#define DATABASE_MODULE "LOG.RDK.DATABASE" - -// Avoid - generic or unclear names -#define MODULE "LOG.RDK.APP" -#define MY_MODULE "LOG.RDK.THING" -``` - -### 2. Performance Optimization -```c -// Check if logging is enabled before expensive operations -if (rdk_dbg_enabled("LOG.RDK.MYAPP", RDK_LOG_DEBUG)) { - char *expensive_debug_info = generate_debug_dump(); - RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.MYAPP", "Debug: %s\n", expensive_debug_info); - free(expensive_debug_info); -} - -// Use appropriate log levels -RDK_LOG(RDK_LOG_FATAL, module, "System crash: %s\n", reason); // System unusable -RDK_LOG(RDK_LOG_ERROR, module, "Failed to connect: %s\n", err); // Error conditions -RDK_LOG(RDK_LOG_WARN, module, "Retrying connection\n"); // Warnings -RDK_LOG(RDK_LOG_NOTICE, module, "Service started\n"); // Important events -RDK_LOG(RDK_LOG_INFO, module, "Processing request\n"); // General info -RDK_LOG(RDK_LOG_DEBUG, module, "Variable x = %d\n", x); // Debug details -RDK_LOG(RDK_LOG_TRACE, module, "Entering function\n"); // Function tracing -``` - -### 3. Thread Safety -```c -// RDK Logger is thread-safe, but avoid race conditions in your logic -void worker_thread(void *arg) { - int thread_id = *(int*)arg; - - RDK_LOG(RDK_LOG_INFO, "LOG.RDK.WORKER", - "Worker thread %d started\n", thread_id); - - // Worker logic... - - RDK_LOG(RDK_LOG_INFO, "LOG.RDK.WORKER", - "Worker thread %d finished\n", thread_id); -} -``` - -### 4. Configuration Management -```c -// Check for override config file -const char* get_config_file() { - if (access("/nvram/debug.ini", F_OK) == 0) { - return "/nvram/debug.ini"; // Development/debug config - } - return "/etc/debug.ini"; // Production config -} - -// Initialize with appropriate config -rdk_Error ret = rdk_logger_init(get_config_file()); -``` - -### 5. Structured Logging -```c -// Include relevant context in log messages -RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.NETWORK", - "Connection failed: host=%s, port=%d, error=%s\n", - hostname, port, strerror(errno)); - -// Use consistent formats for similar events -RDK_LOG(RDK_LOG_INFO, "LOG.RDK.SERVICE", - "SERVICE_START: name=%s, pid=%d, version=%s\n", - service_name, getpid(), version); -``` - -### 6. Cleanup -```c -// Always clean up in signal handlers and exit paths -void signal_handler(int sig) { - RDK_LOG(RDK_LOG_NOTICE, "LOG.RDK.MYAPP", - "Received signal %d, shutting down\n", sig); - rdk_logger_deinit(); - exit(0); -} - -int main() { - signal(SIGINT, signal_handler); - signal(SIGTERM, signal_handler); - - RDK_LOGGER_INIT(); - - // Application logic... - - rdk_logger_deinit(); - return 0; -} -``` - ---- - -**Note**: This documentation covers RDK Logger API version as implemented in the current codebase. For the most up-to-date information, refer to the source code and header files. - diff --git a/docs/MIGRATION_GUIDE.md b/docs/MIGRATION_GUIDE.md deleted file mode 100644 index 9f72735..0000000 --- a/docs/MIGRATION_GUIDE.md +++ /dev/null @@ -1,363 +0,0 @@ -# RDK Logger Migration Guide - -## Overview - -This guide helps developers migrate from other logging systems to RDK Logger and upgrade existing RDK Logger implementations. - -## Migration from printf/fprintf - -### Before (Legacy Code) -```c -#include - -int main() { - printf("Application started\n"); - fprintf(stderr, "Error: Connection failed\n"); - printf("Debug: value = %d\n", value); - return 0; -} -``` - -### After (RDK Logger) -```c -#include "rdk_logger.h" - -#define MODULE_NAME "LOG.RDK.MYAPP" - -int main() { - // Initialize logger - RDK_LOGGER_INIT(); - - RDK_LOG(RDK_LOG_NOTICE, MODULE_NAME, "Application started\n"); - RDK_LOG(RDK_LOG_ERROR, MODULE_NAME, "Error: Connection failed\n"); - RDK_LOG(RDK_LOG_DEBUG, MODULE_NAME, "Debug: value = %d\n", value); - - rdk_logger_deinit(); - return 0; -} -``` - -## Migration from syslog - -### Before (syslog) -```c -#include - -int main() { - openlog("myapp", LOG_PID, LOG_USER); - - syslog(LOG_INFO, "Application started"); - syslog(LOG_ERR, "Connection failed: %s", strerror(errno)); - syslog(LOG_DEBUG, "Processing item %d", item_id); - - closelog(); - return 0; -} -``` - -### After (RDK Logger) -```c -#include "rdk_logger.h" - -#define MODULE_NAME "LOG.RDK.MYAPP" - -int main() { - RDK_LOGGER_INIT(); - - RDK_LOG(RDK_LOG_INFO, MODULE_NAME, "Application started\n"); - RDK_LOG(RDK_LOG_ERROR, MODULE_NAME, "Connection failed: %s\n", strerror(errno)); - RDK_LOG(RDK_LOG_DEBUG, MODULE_NAME, "Processing item %d\n", item_id); - - rdk_logger_deinit(); - return 0; -} -``` - -### Log Level Mapping - -| syslog Level | RDK Logger Level | Description | -|--------------|------------------|-------------| -| LOG_EMERG | RDK_LOG_FATAL | System unusable | -| LOG_ALERT | RDK_LOG_FATAL | Action must be taken immediately | -| LOG_CRIT | RDK_LOG_FATAL | Critical conditions | -| LOG_ERR | RDK_LOG_ERROR | Error conditions | -| LOG_WARNING | RDK_LOG_WARN | Warning conditions | -| LOG_NOTICE | RDK_LOG_NOTICE | Normal but significant condition | -| LOG_INFO | RDK_LOG_INFO | Informational messages | -| LOG_DEBUG | RDK_LOG_DEBUG | Debug-level messages | - -## Migration from Custom Logging - -### Wrapper Approach -If you have existing custom logging macros, you can create wrapper functions: - -```c -// Legacy logging system -#define OLD_LOG_ERROR(fmt, ...) old_log_function(ERROR_LEVEL, fmt, ##__VA_ARGS__) -#define OLD_LOG_INFO(fmt, ...) old_log_function(INFO_LEVEL, fmt, ##__VA_ARGS__) - -// Migration wrapper -#define LOG_ERROR(fmt, ...) RDK_LOG(RDK_LOG_ERROR, MODULE_NAME, fmt, ##__VA_ARGS__) -#define LOG_INFO(fmt, ...) RDK_LOG(RDK_LOG_INFO, MODULE_NAME, fmt, ##__VA_ARGS__) - -// Now replace OLD_LOG_* with LOG_* throughout your codebase -``` - -### Gradual Migration -You can run both systems in parallel during migration: - -```c -#include "rdk_logger.h" -#include "old_logger.h" - -#define DUAL_LOG(level, old_level, fmt, ...) do { \ - RDK_LOG(level, MODULE_NAME, fmt, ##__VA_ARGS__); \ - old_log_function(old_level, fmt, ##__VA_ARGS__); \ -} while(0) - -// Use DUAL_LOG during migration, then switch to RDK_LOG -``` - -## Configuration Migration - -### Converting Log Levels -Create a migration script to convert existing configuration: - -```bash -#!/bin/bash -# migrate_config.sh - -# Convert old format to debug.ini format -old_config="/etc/old_logger.conf" -new_config="/etc/debug.ini" - -echo "# Migrated configuration" > $new_config -echo "LOG.RDK.DEFAULT=WARNING" >> $new_config - -# Parse old configuration and convert -while IFS='=' read -r module level; do - case $level in - "error") new_level="ERROR" ;; - "warning") new_level="WARN" ;; - "info") new_level="INFO" ;; - "debug") new_level="DEBUG" ;; - *) new_level="NOTICE" ;; - esac - echo "LOG.RDK.$module=$new_level" >> $new_config -done < $old_config -``` - -## Advanced Migration Patterns - -### Conditional Compilation -Support both old and new logging during transition: - -```c -#ifdef USE_RDK_LOGGER - #include "rdk_logger.h" - #define APP_LOG(level, fmt, ...) RDK_LOG(level, MODULE_NAME, fmt, ##__VA_ARGS__) - #define APP_LOG_INIT() RDK_LOGGER_INIT() - #define APP_LOG_CLEANUP() rdk_logger_deinit() -#else - #include "old_logger.h" - #define APP_LOG(level, fmt, ...) old_log(level, fmt, ##__VA_ARGS__) - #define APP_LOG_INIT() old_log_init() - #define APP_LOG_CLEANUP() old_log_cleanup() -#endif - -int main() { - APP_LOG_INIT(); - APP_LOG(RDK_LOG_INFO, "Application started\n"); - // ... application code ... - APP_LOG_CLEANUP(); - return 0; -} -``` - -### Performance Comparison -Test performance impact during migration: - -```c -#include - -void performance_test() { - clock_t start, end; - int iterations = 10000; - - // Test RDK Logger performance - start = clock(); - for (int i = 0; i < iterations; i++) { - RDK_LOG(RDK_LOG_DEBUG, MODULE_NAME, "Test message %d\n", i); - } - end = clock(); - - double rdk_time = ((double)(end - start)) / CLOCKS_PER_SEC; - printf("RDK Logger: %f seconds for %d messages\n", rdk_time, iterations); -} -``` - -## Common Migration Issues - -### Issue 1: Missing Newlines -**Problem**: RDK Logger expects newlines in format strings. -```c -// Wrong -RDK_LOG(RDK_LOG_INFO, MODULE_NAME, "Message"); - -// Correct -RDK_LOG(RDK_LOG_INFO, MODULE_NAME, "Message\n"); -``` - -### Issue 2: Module Name Format -**Problem**: Incorrect module naming convention. -```c -// Wrong -RDK_LOG(RDK_LOG_INFO, "MYAPP", "Message\n"); - -// Correct -RDK_LOG(RDK_LOG_INFO, "LOG.RDK.MYAPP", "Message\n"); -``` - -### Issue 3: Initialization Order -**Problem**: Logging before initialization. -```c -// Wrong -int main() { - RDK_LOG(RDK_LOG_INFO, MODULE_NAME, "Starting\n"); // Will fail - RDK_LOGGER_INIT(); -} - -// Correct -int main() { - RDK_LOGGER_INIT(); - RDK_LOG(RDK_LOG_INFO, MODULE_NAME, "Starting\n"); -} -``` - -### Issue 4: Thread Safety -**Problem**: Initialization in multi-threaded environment. -```c -// Wrong - race condition -void thread_function() { - RDK_LOGGER_INIT(); // Multiple threads calling init - // ... -} - -// Correct - initialize once in main thread -int main() { - RDK_LOGGER_INIT(); - - // Create threads after initialization - pthread_create(&thread, NULL, thread_function, NULL); -} -``` - -## Testing Migration - -### Validation Script -```bash -#!/bin/bash -# validate_migration.sh - -echo "Testing RDK Logger migration..." - -# Test 1: Configuration file exists -if [ ! -f /etc/debug.ini ]; then - echo "ERROR: debug.ini not found" - exit 1 -fi - -# Test 2: Module names follow convention -if ! grep -q "LOG.RDK." /etc/debug.ini; then - echo "WARNING: No LOG.RDK modules found in config" -fi - -# Test 3: Test application logging -./test_app > /tmp/test_output.log 2>&1 - -if grep -q "LOG.RDK" /tmp/test_output.log; then - echo "SUCCESS: RDK Logger output detected" -else - echo "ERROR: No RDK Logger output found" - exit 1 -fi - -echo "Migration validation complete" -``` - -### Unit Test Example -```c -#include -#include "rdk_logger.h" - -void test_migration() { - // Test initialization - assert(RDK_LOGGER_INIT() == RDK_SUCCESS); - - // Test logging levels - assert(rdk_dbg_enabled("LOG.RDK.TEST", RDK_LOG_ERROR) == TRUE); - - // Test cleanup - assert(rdk_logger_deinit() == RDK_SUCCESS); - - printf("Migration tests passed\n"); -} -``` - -## Migration Checklist - -- [ ] Review existing logging calls and categorize by log level -- [ ] Create module name mapping (old names → LOG.RDK.* names) -- [ ] Update configuration files to debug.ini format -- [ ] Replace logging function calls with RDK_LOG macros -- [ ] Add RDK_LOGGER_INIT() and rdk_logger_deinit() calls -- [ ] Update build system to link RDK Logger libraries -- [ ] Test logging output and configuration -- [ ] Validate runtime log level changes work -- [ ] Update documentation and deployment scripts -- [ ] Train team on new logging system usage - -## Post-Migration Optimization - -### 1. Performance Tuning -```c -// Use conditional logging for expensive debug operations -if (rdk_dbg_enabled(MODULE_NAME, RDK_LOG_DEBUG)) { - char *debug_dump = expensive_debug_function(); - RDK_LOG(RDK_LOG_DEBUG, MODULE_NAME, "Debug: %s\n", debug_dump); - free(debug_dump); -} -``` - -### 2. Configuration Optimization -```ini -# Production config - minimal logging -LOG.RDK.DEFAULT=ERROR - -# Development config - detailed logging -LOG.RDK.DEFAULT=DEBUG -LOG.RDK.NETWORK=TRACE -LOG.RDK.DATABASE=DEBUG -``` - -### 3. Monitoring Integration -```c -// Add metrics for log message rates -void log_with_metrics(rdk_LogLevel level, const char *module, - const char *format, ...) { - static int log_count = 0; - log_count++; - - if (log_count % 1000 == 0) { - RDK_LOG(RDK_LOG_INFO, "LOG.RDK.METRICS", - "Logged %d messages\n", log_count); - } - - va_list args; - va_start(args, format); - rdk_logger_msg_vsprintf(level, module, format, args); - va_end(args); -} -``` - -This migration guide provides a comprehensive approach to transitioning to RDK Logger while maintaining system stability and performance. \ No newline at end of file diff --git a/docs/QUICK_REFERENCE.md b/docs/QUICK_REFERENCE.md deleted file mode 100644 index d2ab5d3..0000000 --- a/docs/QUICK_REFERENCE.md +++ /dev/null @@ -1,336 +0,0 @@ -# RDK Logger Quick Reference - -## Essential Functions - -### Initialization -```c -#include "rdk_logger.h" - -// Standard initialization (uses /etc/debug.ini or /nvram/debug.ini) -RDK_LOGGER_INIT(); - -// Custom config file -rdk_logger_init("/path/to/custom/debug.ini"); - -// Extended initialization with file logging -rdk_logger_ext_config_t config = { - .fileName = "app.log", - .logdir = "/var/log/", - .maxSize = 1024*1024, // 1MB - .maxCount = 5 // Keep 5 files -}; -rdk_logger_ext_init(&config); - -// Cleanup -rdk_logger_deinit(); -``` - -### Logging -```c -// Basic logging -RDK_LOG(RDK_LOG_INFO, "LOG.RDK.MYAPP", "Message\n"); - -// Formatted logging -RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.MYAPP", "Error %d: %s\n", errno, strerror(errno)); - -// Performance-conscious logging -if (rdk_dbg_enabled("LOG.RDK.MYAPP", RDK_LOG_DEBUG)) { - char *expensive_data = generate_debug_info(); - RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.MYAPP", "Debug: %s\n", expensive_data); - free(expensive_data); -} -``` - -## Log Levels (Priority Order) - -| Level | Macro | When to Use | -|-------|-------|-------------| -| FATAL | `RDK_LOG_FATAL` | System crash, unusable | -| ERROR | `RDK_LOG_ERROR` | Operation failures | -| WARN | `RDK_LOG_WARN` | Potential problems | -| NOTICE| `RDK_LOG_NOTICE` | Important events | -| INFO | `RDK_LOG_INFO` | General information | -| DEBUG | `RDK_LOG_DEBUG` | Debugging details | -| TRACE | `RDK_LOG_TRACE` | Function tracing | - -## Configuration (debug.ini) - -```ini -# Default level for all modules -LOG.RDK.DEFAULT=WARNING - -# Module-specific levels -LOG.RDK.NETWORK=DEBUG -LOG.RDK.AUDIO=INFO -LOG.RDK.VIDEO=NOTICE -LOG.RDK.TEST=NONE -``` - -### Config File Locations (Priority Order) -1. `/nvram/debug.ini` (override - highest priority) -2. `/etc/debug.ini` (default) -3. Custom path via `rdk_logger_init(path)` - -## Runtime Control - -### rdklogctrl Command -```bash -# Set log level for module -rdklogctrl - -# Examples -rdklogctrl myapp LOG.RDK.NETWORK DEBUG -rdklogctrl receiver LOG.RDK.AUDIO INFO -rdklogctrl player LOG.RDK.VIDEO ERROR - -# Disable specific level (~ prefix) -rdklogctrl myapp LOG.RDK.NETWORK ~DEBUG - -# Available levels -FATAL ERROR WARN NOTICE INFO DEBUG TRACE NONE -``` - -### Programmatic Control -```c -// Check if level is enabled -if (rdk_dbg_enabled("LOG.RDK.MYAPP", RDK_LOG_DEBUG)) { - // Debug logging is enabled -} - -// Enable/disable level at runtime -rdk_logger_enable_logLevel("LOG.RDK.MYAPP", RDK_LOG_DEBUG, TRUE); // Enable -rdk_logger_enable_logLevel("LOG.RDK.MYAPP", RDK_LOG_DEBUG, FALSE); // Disable - -// Convert string to log level -rdk_LogLevel level = rdk_logger_level_from_string("INFO"); -``` - -## Module Naming Convention - -### Correct Format -```c -#define MODULE_NAME "LOG.RDK.MYAPP" -#define NETWORK_MODULE "LOG.RDK.NETWORK" -#define AUDIO_MODULE "LOG.RDK.AUDIO" -``` - -### Common Mistakes -```c -// ❌ Wrong - missing LOG.RDK prefix -RDK_LOG(RDK_LOG_INFO, "MYAPP", "Message\n"); - -// ❌ Wrong - case sensitivity -RDK_LOG(RDK_LOG_INFO, "log.rdk.myapp", "Message\n"); - -// ❌ Wrong - extra spaces -RDK_LOG(RDK_LOG_INFO, "LOG.RDK. MYAPP", "Message\n"); - -// ✅ Correct -RDK_LOG(RDK_LOG_INFO, "LOG.RDK.MYAPP", "Message\n"); -``` - -## Common Patterns - -### Application Template -```c -#include "rdk_logger.h" -#include - -#define MODULE_NAME "LOG.RDK.MYAPP" - -void cleanup_handler(int sig) { - RDK_LOG(RDK_LOG_NOTICE, MODULE_NAME, "Shutting down (signal %d)\n", sig); - rdk_logger_deinit(); - exit(0); -} - -int main() { - // Setup signal handlers - signal(SIGTERM, cleanup_handler); - signal(SIGINT, cleanup_handler); - - // Initialize logger - if (RDK_LOGGER_INIT() != RDK_SUCCESS) { - fprintf(stderr, "Logger init failed\n"); - return 1; - } - - RDK_LOG(RDK_LOG_NOTICE, MODULE_NAME, "Application started\n"); - - // Main application logic - RDK_LOG(RDK_LOG_INFO, MODULE_NAME, "Processing...\n"); - - // Cleanup - RDK_LOG(RDK_LOG_NOTICE, MODULE_NAME, "Application finished\n"); - rdk_logger_deinit(); - return 0; -} -``` - -### Error Handling Pattern -```c -int connect_to_server(const char *hostname, int port) { - RDK_LOG(RDK_LOG_INFO, MODULE_NAME, "Connecting to %s:%d\n", hostname, port); - - int sock = socket(AF_INET, SOCK_STREAM, 0); - if (sock < 0) { - RDK_LOG(RDK_LOG_ERROR, MODULE_NAME, - "Socket creation failed: %s\n", strerror(errno)); - return -1; - } - - // Connection logic... - - if (connect_result < 0) { - RDK_LOG(RDK_LOG_ERROR, MODULE_NAME, - "Connection to %s:%d failed: %s\n", - hostname, port, strerror(errno)); - close(sock); - return -1; - } - - RDK_LOG(RDK_LOG_NOTICE, MODULE_NAME, - "Successfully connected to %s:%d\n", hostname, port); - return sock; -} -``` - -### Performance-Conscious Logging -```c -void process_data(const data_t *data) { - RDK_LOG(RDK_LOG_INFO, MODULE_NAME, "Processing data batch\n"); - - // Only generate expensive debug info if debug logging is enabled - if (rdk_dbg_enabled(MODULE_NAME, RDK_LOG_DEBUG)) { - char debug_info[1024]; - generate_debug_summary(data, debug_info, sizeof(debug_info)); - RDK_LOG(RDK_LOG_DEBUG, MODULE_NAME, "Data details: %s\n", debug_info); - } - - // Trace function entry/exit only if trace is enabled - if (rdk_dbg_enabled(MODULE_NAME, RDK_LOG_TRACE)) { - RDK_LOG(RDK_LOG_TRACE, MODULE_NAME, "Entering %s\n", __FUNCTION__); - } - - // Process data... - - if (rdk_dbg_enabled(MODULE_NAME, RDK_LOG_TRACE)) { - RDK_LOG(RDK_LOG_TRACE, MODULE_NAME, "Exiting %s\n", __FUNCTION__); - } -} -``` - -## Build Integration - -### Makefile -```makefile -# Compiler flags -CFLAGS += -I/usr/include/rdklogger - -# Linker flags -LDFLAGS += -lrdkloggers -llog4c -lglib-2.0 - -# Example target -myapp: myapp.c - $(CC) $(CFLAGS) -o $@ $< $(LDFLAGS) -``` - -### CMake -```cmake -# Find required libraries -find_package(PkgConfig REQUIRED) -pkg_check_modules(GLIB REQUIRED glib-2.0) - -# Link libraries -target_link_libraries(myapp - rdkloggers - log4c - ${GLIB_LIBRARIES} -) - -# Include directories -target_include_directories(myapp PRIVATE - /usr/include/rdklogger - ${GLIB_INCLUDE_DIRS} -) -``` - -## Debugging Tips - -### Check Configuration -```bash -# Verify config file exists and is readable -cat /etc/debug.ini - -# Test with specific module -grep "LOG.RDK.MYAPP" /etc/debug.ini - -# Check default level -grep "LOG.RDK.DEFAULT" /etc/debug.ini -``` - -### Test Logging -```c -// Test program to verify logging works -#include "rdk_logger.h" - -int main() { - printf("Testing RDK Logger...\n"); - - if (RDK_LOGGER_INIT() != RDK_SUCCESS) { - printf("❌ Init failed\n"); - return 1; - } - printf("✅ Init succeeded\n"); - - const char *module = "LOG.RDK.TEST"; - - printf("Testing log levels:\n"); - RDK_LOG(RDK_LOG_FATAL, module, "❌ FATAL message\n"); - RDK_LOG(RDK_LOG_ERROR, module, "🔴 ERROR message\n"); - RDK_LOG(RDK_LOG_WARN, module, "🟡 WARN message\n"); - RDK_LOG(RDK_LOG_NOTICE, module, "🔵 NOTICE message\n"); - RDK_LOG(RDK_LOG_INFO, module, "ℹ️ INFO message\n"); - RDK_LOG(RDK_LOG_DEBUG, module, "🐛 DEBUG message\n"); - RDK_LOG(RDK_LOG_TRACE, module, "🔍 TRACE message\n"); - - rdk_logger_deinit(); - printf("✅ Test completed\n"); - return 0; -} -``` - -### Runtime Control Test -```bash -# Start your application in background -./myapp & -APP_PID=$! - -# Change log level -rdklogctrl myapp LOG.RDK.TEST DEBUG - -# Check if change took effect (application should show more logs) - -# Cleanup -kill $APP_PID -``` - -## Error Codes - -| Code | Meaning | Action | -|------|---------|---------| -| 0 | `RDK_SUCCESS` | Operation successful | -| Non-zero | Various errors | Check config file, permissions, dependencies | - -## Dependencies - -### Required Libraries -- `librdkloggers` - RDK Logger library -- `liblog4c` - Log4C logging framework -- `libglib-2.0` - GLib utility library - -### Optional Tools -- `rdklogctrl` - Runtime log control utility -- `rdklogmilestone` - Milestone logging utility - -This quick reference provides the most commonly needed information for day-to-day RDK Logger usage. \ No newline at end of file diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..4a515e5 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,550 @@ +# RDK Logger + +RDK Logger is a logging framework for all RDK-B middleware components. It provides centralized, configurable, and runtime-controllable logging with fine-grained control over log levels, formatting, and output destinations for different modules and components. + +RDK Logger provides a unified logging interface that standardizes how RDK-B components generate and manage log messages. It enables dynamic runtime control of logging behavior, allowing operators to adjust logging levels and verbosity without requiring system restarts. It optimizes system performance by implementing efficient filtering mechanisms that minimize logging overhead when verbose logging is disabled. + +RDK Logger uses a configuration-driven architecture where each component maintains its own logging context within a centralized logging system. The framework handles log message formatting, filtering, routing, and output management with thread-safe operations and minimal performance impact on host applications. + +```mermaid +graph LR + subgraph "External Systems" + RemoteMgmt["Remote Management"] + LocalUI["Local Web UI"] + AdminTools["Admin Tools
rdklogctrl"] + MonitorSys["Monitoring Systems"] + end + + subgraph "RDK-B Platform" + subgraph "Remote Management Agents" + ProtocolAgents["TR-069/WebPA/TR-369
Protocol Agents"] + end + + subgraph "Logging Framework" + RDKLogger["RDKLogger
(Logging Framework)"] + end + + subgraph "RDK-B Core Components" + CMAgent["CM Agent"] + WiFiAgent["CcspWiFiAgent/OneWiFi"] + PandM["CcspPandM"] + PSM["PSM"] + OtherComp["Other Components"] + end + + subgraph "System Layer" + Log4C["Log4C Backend"] + Linux["Linux Kernel
(System Logger)"] + end + end + + %% External connections + RemoteMgmt -->|TR-069/WebPA/TR-369| ProtocolAgents + LocalUI -->|HTTP/HTTPS| ProtocolAgents + AdminTools -->|UDP Control| RDKLogger + MonitorSys -->|Log Analysis| RDKLogger + + %% Upper layer to RDK Logger + ProtocolAgents -->|RDK_LOG APIs| RDKLogger + + %% RDK-B Components to Logger + CMAgent -->|RDK_LOG APIs| RDKLogger + WiFiAgent -->|RDK_LOG APIs| RDKLogger + PandM -->|RDK_LOG APIs| RDKLogger + PSM -->|RDK_LOG APIs| RDKLogger + OtherComp -->|RDK_LOG APIs| RDKLogger + + %% System Layer interactions + RDKLogger <-->|Log4C APIs| Log4C + Log4C <-->|System Calls| Linux + + classDef external fill:#fff3e0,stroke:#ef6c00,stroke-width:2px; + classDef rdklogger fill:#e3f2fd,stroke:#1976d2,stroke-width:3px; + classDef rdkbComponent fill:#e8f5e8,stroke:#2e7d32,stroke-width:2px; + classDef system fill:#fce4ec,stroke:#c2185b,stroke-width:2px; + + class RemoteMgmt,LocalUI,AdminTools,MonitorSys external; + class RDKLogger rdklogger; + class ProtocolAgents,CMAgent,WiFiAgent,PandM,PSM,OtherComp rdkbComponent; + class Log4C,Linux system; +``` + +**Key Features & Responsibilities**: + +- **Centralized Logging Framework**: Provides a unified logging API and configuration system for all RDK-B middleware components, ensuring consistent logging behavior across the entire platform +- **Dynamic Runtime Control**: Enables real-time adjustment of log levels and verbosity for individual modules through the `rdklogctrl` utility without requiring service restarts +- **Module-Specific Configuration**: Supports independent log level configuration for each component through the `debug.ini` file, allowing fine-grained control over logging behavior +- **Performance Optimization**: Implements efficient filtering mechanisms that minimize CPU and memory overhead when verbose logging is disabled, crucial for resource-constrained embedded systems +- **Multi-Level Logging Support**: Provides comprehensive log level hierarchy (TRACE, DEBUG, INFO, NOTICE, WARN, ERROR, FATAL) with configurable verbosity control +- **Thread-Safe Operations**: Ensures safe concurrent access to logging functions across multi-threaded RDK-B components without requiring external synchronization +- **Configuration Management**: Handles automatic detection of configuration file overrides with three-tier priority system (`/opt/debug.ini` highest, `/nvram/debug.ini` second, `/etc/debug.ini` default) and runtime configuration updates +- **Log Format Standardization**: Enforces consistent timestamp, module identification, and message formatting across all RDK-B components for improved log analysis and monitoring + +## Design + +RDK Logger is a logging abstraction layer that sits between RDK-B applications and the underlying Log4C logging infrastructure. The design follows a modular approach where core logging functionality is separated from configuration management, runtime control, and output formatting. This separation enables independent evolution of each subsystem while maintaining backward compatibility and minimizing performance impact on client applications. + +The architecture uses configuration-driven behavior where all logging policies are externalized to the `debug.ini` configuration file. System administrators and developers can adjust logging behavior without code changes or application restarts. The framework implements a three-tier configuration system with priority-based file selection: first checking `/opt/debug.ini` for platform-specific overrides, then `/nvram/debug.ini` for runtime overrides, and finally falling back to `/etc/debug.ini` for default system-wide settings. + +Northbound interactions with RDK-B middleware components are handled through a high-performance C API that provides printf-style logging functions. The API design minimizes function call overhead and includes compile-time optimizations for disabled log levels. Southbound interactions with the Log4C library and system logging facilities are abstracted through a pluggable backend architecture. + +The IPC mechanism uses UDP sockets for runtime log level control, enabling the `rdklogctrl` utility to communicate with running processes. This approach ensures that runtime control operations have minimal impact on system performance. + +Data persistence and storage management are handled through in-memory configuration caching and file-based persistence. The framework loads configuration at startup, caches it in memory for performance, and provides mechanisms for runtime updates. Log output persistence is delegated to the underlying Log4C system, which handles file rotation, compression, and storage management. + +```mermaid +flowchart TD + subgraph "RDK Logger Architecture" + subgraph "Public API Layer" + API[Core Logging API
rdk_logger.h] + Macros[RDK_LOG Macros] + end + + subgraph "Configuration Layer" + Config[Configuration Manager] + Cache[Configuration Cache] + end + + subgraph "Runtime Control" + DynLog[Dynamic Logger] + UDPServer[UDP Control Server] + end + + subgraph "Logging Subsystems" + Debug[Debug Support] + Milestone[Milestone Logging] + OnBoard[Onboarding Support] + end + + subgraph "Output Management" + Formatter[Message Formatter] + Filter[Level Filter] + Router[Output Router] + end + + subgraph "Backend Integration" + Log4C[Log4C Backend] + FileOut[File Output] + ConsoleOut[Console Output] + end + end + + API --> Config + Macros --> Filter + Config --> Cache + Cache --> Filter + + DynLog --> UDPServer + UDPServer --> Cache + + API --> Debug + Debug --> Milestone + Milestone --> OnBoard + + Filter --> Formatter + Formatter --> Router + Router --> Log4C + Router --> FileOut + Router --> ConsoleOut + + classDef api fill:#e1f5fe,stroke:#0277bd,stroke-width:2px; + classDef config fill:#fff8e1,stroke:#f57f17,stroke-width:2px; + classDef runtime fill:#e8f5e8,stroke:#2e7d32,stroke-width:2px; + classDef subsystem fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px; + classDef output fill:#fff3e0,stroke:#ef6c00,stroke-width:2px; + classDef backend fill:#fce4ec,stroke:#c2185b,stroke-width:2px; + + class API,Macros api; + class Config,Cache config; + class DynLog,UDPServer runtime; + class Debug,Milestone,OnBoard subsystem; + class Formatter,Filter,Router output; + class Log4C,FileOut,ConsoleOut backend; +``` + +### Prerequisites and Dependencies + +**Build-Time Dependencies and Configuration:** + +RDK Logger uses autotools-based configuration with automatic feature detection. The following build flags are auto-detected or externally defined: + +| Build Flag | Detection Method | Purpose | Default | +|------------|------------------|---------|---------| +| `HAVE_SYSTEMD` | Auto-detected via `PKG_CHECK_MODULES([SYSTEMD], [libsystemd >= 209])` | Enable systemd journal logging support when libsystemd is available | Auto-detected | +| `HAVE_SYSLOG_H` | Auto-detected via `AC_CHECK_HEADERS([syslog.h])` | Enable syslog output support when syslog.h is available | Auto-detected | +| `LOGMILESTONE` | Externally defined (Yocto/build system) | Controls milestone log file path (`/opt/logs/` vs `/rdklogs/logs/`) | Defined externally | +| `DEBUG_CONF_FILE` | Makefile compile flag | Set default configuration file name to `"debug.ini"` | `"debug.ini"` | + +**RDK-B Platform and Integration Requirements** + +- **RDK-B Components**: + - No mandatory RDK-B middleware dependencies (RDK Logger is a foundational component) + - Integration with `systemd` for service management in systemd-enabled builds + - Coordination with `rdk-logger` recipe in Yocto build system +- **HAL Dependencies**: No direct HAL interface dependencies (operates at middleware layer) +- **Systemd Services**: No specific systemd service dependencies, but integrates with systemd journal when available +- **Message Bus**: No RBus registration required (RDK Logger operates below the message bus layer) +- **Configuration Files**: + - `/etc/debug.ini` (default system-wide configuration file, must exist) + - `/nvram/debug.ini` (optional runtime override configuration, second priority) + - `/opt/debug.ini` (optional platform-specific override configuration, first priority) + - Proper file system permissions for configuration file access +- **Startup Order**: Must initialize before any RDK-B component that uses logging (typically first in startup sequence) + +
+ +**Threading Model:** + +RDK Logger implements a library-based architecture with minimal threading, designed for high-performance integration into multi-threaded RDK-B applications. Unlike service-based components, RDK Logger operates as a shared library that provides thread-safe logging APIs to client applications. + +| Thread & Function | Purpose | Cycle/Timeout | Synchronization | +|-------------------|---------|----------------|------------------| +| **Client Application Thread**
`RDK_LOG()` calls | Primary logging interface for client applications | Event-driven API calls, immediate log processing, thread-safe Log4C integration | Thread-safe Log4C backend, atomic log level checks | +| **UDP Control Listener**
`rdk_dyn_log_process_pending_request()` | Runtime log level control via rdklogctrl utility | Non-blocking UDP socket polling, immediate configuration updates | Socket-based IPC, configuration cache updates | +| **Configuration Manager**
`rdk_logger_init()` / `rdk_logger_deinit()` | Library initialization and cleanup operations | One-time initialization per process, configuration file parsing | File system synchronization, memory management | + +### Component State Flow + +**Initialization to Active State** + +RDK Logger follows a well-defined initialization sequence that ensures proper configuration loading, backend initialization, and runtime control setup before becoming available for client applications. + +```mermaid +sequenceDiagram + participant System as System Startup/Application + participant Logger as RDK Logger Core + participant Config as Configuration Manager + participant Log4C as Log4C Backend + participant DynCtrl as Dynamic Controller + participant FileSystem as File System + + System->>Logger: RDK_LOGGER_INIT() + Note over Logger: State: Initializing
Check file paths, setup logging context + + Logger->>FileSystem: Check /opt/debug.ini existence + + alt /opt/debug.ini exists + FileSystem-->>Logger: Override file available + Logger->>Config: Load /opt/debug.ini + else Check second priority + Logger->>FileSystem: Check /nvram/debug.ini existence + alt /nvram/debug.ini exists + FileSystem-->>Logger: Override file available + Logger->>Config: Load /nvram/debug.ini + else Use default configuration + FileSystem-->>Logger: Use default config + Logger->>Config: Load /etc/debug.ini + end + end + + Config->>FileSystem: Parse configuration file + FileSystem-->>Config: Configuration data + Config-->>Logger: Configuration loaded successfully + Note over Logger: State: LoadingConfig → InitializingBackend + + Logger->>Log4C: Initialize Log4C backend + Log4C-->>Logger: Backend initialization complete + Note over Logger: State: InitializingBackend → StartingDynamicControl + + Logger->>DynCtrl: Start UDP listener for runtime control + DynCtrl-->>Logger: Dynamic control service active + Note over Logger: State: StartingDynamicControl → Active + + Logger->>System: RDK_SUCCESS (Initialization Complete) + + loop Runtime Operations + Note over Logger: State: Active
Process log messages, handle runtime updates + System->>Logger: RDK_LOG() calls + Logger->>Logger: Filter, format, and route messages + + DynCtrl->>Config: Runtime level changes via rdklogctrl + Config->>Logger: Update cached configuration + end + + System->>Logger: rdk_logger_deinit() + Note over Logger: State: Active → Shutdown + Logger->>DynCtrl: Stop dynamic control service + Logger->>Log4C: Cleanup backend resources + Logger->>System: Shutdown complete +``` + +**Runtime State Changes and Context Switching** + +RDK Logger maintains several operational contexts that can change during runtime based on external events and configuration updates. + +**State Change Triggers:** + +- **Configuration File Updates**: Detection of changes to debug.ini files triggers configuration reload and cache updates +- **Dynamic Log Level Changes**: Runtime commands via `rdklogctrl` trigger immediate log level updates for specific modules +- **Backend Failures**: Log4C backend errors trigger fallback to direct stdout/stderr output to maintain logging availability +- **Memory Pressure**: High memory usage can trigger log message queuing and batch processing optimizations + +**Context Switching Scenarios:** + +- **Configuration Override Detection**: Three-tier priority system checking `/opt/debug.ini`, then `/nvram/debug.ini`, then `/etc/debug.ini` based on file availability and access permissions +- **Output Destination Switching**: Automatic fallback from file output to console output when log files become unavailable +- **Debug Mode Activation**: Enhanced logging and diagnostic output when debug flags are enabled through configuration or runtime commands + +### Call Flow + +**Initialization Call Flow:** + +```mermaid +sequenceDiagram + participant App as RDK-B Application + participant RDKLog as RDK Logger API + participant ConfigMgr as Configuration Manager + participant Log4C as Log4C Backend + participant DynLog as Dynamic Logger + + App->>RDKLog: RDK_LOGGER_INIT() + RDKLog->>RDKLog: Check configuration file paths + RDKLog->>ConfigMgr: Initialize configuration system + ConfigMgr->>ConfigMgr: Parse debug.ini file + ConfigMgr-->>RDKLog: Configuration loaded + RDKLog->>Log4C: Initialize Log4C backend + Log4C-->>RDKLog: Backend ready + RDKLog->>DynLog: Start dynamic control listener + DynLog-->>RDKLog: UDP listener active + RDKLog-->>App: RDK_SUCCESS (Active State) +``` + +**Request Processing Call Flow:** + +The most critical flow is the standard log message processing, which must be highly optimized for performance: + +```mermaid +sequenceDiagram + participant App as RDK-B Application + participant RDKLog as RDK Logger Macro + participant Filter as Level Filter + participant Formatter as Message Formatter + participant Backend as Log4C/Output + + App->>RDKLog: RDK_LOG(level, module, format, ...) + RDKLog->>Filter: Check if level enabled for module + + alt Log level enabled + Filter-->>RDKLog: Level check passed + RDKLog->>Formatter: Format message with timestamp, module, level + Formatter->>Backend: Send formatted message + Backend-->>Formatter: Message written + Formatter-->>RDKLog: Success + RDKLog-->>App: Message logged + else Log level disabled + Filter-->>RDKLog: Level check failed (no-op) + RDKLog-->>App: Message filtered (fast return) + end +``` + +**Dynamic Control Call Flow:** + +```mermaid +sequenceDiagram + participant Admin as System Administrator + participant RdkLogCtrl as rdklogctrl utility + participant UDPListener as UDP Control Listener + participant ConfigCache as Configuration Cache + participant TargetApp as Target Application + + Admin->>RdkLogCtrl: rdklogctrl process_name module_name log_level + RdkLogCtrl->>UDPListener: UDP control message + UDPListener->>ConfigCache: Update log level for module + ConfigCache->>TargetApp: Apply new log level immediately + TargetApp-->>ConfigCache: Level update acknowledged + ConfigCache-->>UDPListener: Update successful + UDPListener-->>RdkLogCtrl: Control command completed + RdkLogCtrl-->>Admin: Log level changed successfully +``` + +## Internal Modules + +RDK Logger is composed of several specialized modules, each responsible for specific aspects of the logging functionality. The modular design enables maintainability and allows for independent testing and optimization of each component. + +| Module/Class | Description | Key Files | +|-------------|------------|-----------| +| **Core Logging API** | Main application interface providing RDK_LOG macros and initialization functions | `include/rdk_logger.h`, `src/rdk_logger_init.c`, `src/rdk_debug.c` | +| **Configuration Manager** | Handles parsing, caching, and management of debug.ini configuration files | `src/rdk_logger_init.c`, `src/rdk_debug_priv.c` | +| **Dynamic Logger** | Runtime control system for changing log levels via UDP socket communication | `src/rdk_dynamic_logger.c`, `src/include/rdk_dynamic_logger.h` | +| **Debug Support** | Enhanced debugging capabilities, internal diagnostics, and development tools | `src/rdk_debug.c`, `src/rdk_debug_priv.c`, `include/rdk_debug.h`, `src/include/rdk_debug_priv.h` | +| **Milestone Logging** | Special-purpose logging for system milestones and significant events | `src/rdk_logger_milestone.c`, `include/rdk_logger_milestone.h`, `scripts/logMilestone.sh` | +| **Onboarding Support** | Utilities for component integration and initialization assistance | `src/rdk_logger_onboard.c`, `utils/rdk_logger_onboard_main.c` | +| **Runtime Control Utilities** | Command-line tools for log level management and system interaction | `utils/rdklogctrl.c`, `utils/rdklogmilestone.c` | + +## Component Interactions + +RDK Logger serves as a foundational component that interfaces with multiple layers of the RDK-B architecture, from application-level middleware components down to system-level services and external administrative tools. + +### Interaction Matrix + +| Target Component/Layer | Interaction Purpose | Key APIs/Endpoints | +|------------------------|-------------------|------------------| +| **RDK-B Middleware Components** | +| CcspCMAgent | Cable modem status and configuration logging | `RDK_LOG()`, module: `LOG.RDK.CM` | +| CcspTr069Pa | TR-069 protocol events and diagnostic logging | `RDK_LOG()`, module: `LOG.RDK.TR069` | +| CcspWiFiAgent/OneWiFi | WiFi operations, connection events, security logging | `RDK_LOG()`, module: `LOG.RDK.WIFI` | +| CcspPandM | Platform and management events, system status | `RDK_LOG()`, module: `LOG.RDK.PAM` | +| CcspPsm | Parameter storage and retrieval operations | `RDK_LOG()`, module: `LOG.RDK.PSM` | +| WAN Manager | WAN interface management and failover events | `RDK_LOG()`, module: `LOG.RDK.WANMGR` | +| **System & Platform Layers** | +| Log4C Library | Backend log message formatting and file management | `log4c_init()`, `log4c_category_log()`, configuration via log4crc | +| System Logger (syslog) | System-wide log integration and kernel message coordination | Direct syslog API calls, facility LOG_USER | +| File System | Configuration file access and log file storage | `/opt/debug.ini`, `/nvram/debug.ini`, `/etc/debug.ini`, `/var/log/*` | +| systemd Journal | Modern Linux logging integration | Journal API integration when available | +| Network Services | UDP socket communication for runtime control | UDP port 12035, localhost interface | + +**Events Published by RDK Logger:** + +| Event Name | Event Topic/Path | Trigger Condition | Subscriber Components | +|------------|-----------------|-------------------|---------------------| +| Log Level Change | UDP control message | Dynamic log level modification via rdklogctrl | All RDK-B components using affected module | +| Configuration Reload | Internal event | debug.ini file modification detection | Internal configuration cache, all active loggers | +| Backend Failure | Internal diagnostic | Log4C backend initialization or runtime failure | Internal fallback mechanisms, system administrators | +| Milestone Event | Log message | System milestone reached (boot, configuration, etc.) | Log monitoring systems, diagnostic tools | + +### IPC Flow Patterns + +**Primary IPC Flow - Standard Logging:** + +```mermaid +sequenceDiagram + participant Client as RDK-B Component + participant RDKLogger as RDK Logger Library + participant ConfigCache as Configuration Cache + participant Log4C as Log4C Backend + participant FileSystem as File System + + Client->>RDKLogger: RDK_LOG(level, module, message, ...) + Note over RDKLogger: Fast path: Check log level enabled + RDKLogger->>ConfigCache: Query level for module (atomic read) + ConfigCache-->>RDKLogger: Level enabled/disabled + + alt Log level enabled + RDKLogger->>RDKLogger: Format message with timestamp, module ID + RDKLogger->>Log4C: log4c_category_log(category, priority, message) + Log4C->>FileSystem: Write formatted log to file + FileSystem-->>Log4C: Write acknowledged + Log4C-->>RDKLogger: Log operation complete + RDKLogger-->>Client: Success (minimal overhead) + else Log level disabled + Note over RDKLogger: Fast return - no processing + RDKLogger-->>Client: No-op return (optimized path) + end +``` + +**Dynamic Control Flow - Runtime Log Level Changes:** + +```mermaid +sequenceDiagram + participant Admin as System Administrator + participant RdkLogCtrl as rdklogctrl Utility + participant UDPListener as RDK Logger UDP Listener + participant ConfigCache as Configuration Cache + participant ActiveLoggers as Active Logger Instances + + Admin->>RdkLogCtrl: rdklogctrl myapp LOG.RDK.WIFI DEBUG + RdkLogCtrl->>RdkLogCtrl: Parse and validate command parameters + RdkLogCtrl->>UDPListener: UDP control packet (port 12035) + Note over UDPListener: Process: myapp, Module: LOG.RDK.WIFI, Level: DEBUG + + UDPListener->>ConfigCache: Update log level for module (atomic write) + ConfigCache->>ActiveLoggers: Propagate level change to all instances + Note over ActiveLoggers: Immediate effect - new log level active + + ActiveLoggers-->>ConfigCache: Update confirmation + ConfigCache-->>UDPListener: Level change successful + UDPListener-->>RdkLogCtrl: Success response + RdkLogCtrl-->>Admin: "Log level changed successfully" +``` + +**Configuration Loading Flow:** + +```mermaid +sequenceDiagram + participant App as Application Startup + participant RDKLogger as RDK Logger Init + participant FileSystem as File System + participant ConfigParser as Configuration Parser + participant ConfigCache as Configuration Cache + + App->>RDKLogger: RDK_LOGGER_INIT() + RDKLogger->>FileSystem: Check /opt/debug.ini (first priority) + + alt /opt/debug.ini exists and is readable + FileSystem-->>RDKLogger: Override file available + RDKLogger->>ConfigParser: Parse /opt/debug.ini + else Check second priority + RDKLogger->>FileSystem: Check /nvram/debug.ini (second priority) + alt /nvram/debug.ini exists and is readable + FileSystem-->>RDKLogger: Override file available + RDKLogger->>ConfigParser: Parse /nvram/debug.ini + else Use default configuration + FileSystem-->>RDKLogger: Use default config + RDKLogger->>ConfigParser: Parse /etc/debug.ini + end + end + + ConfigParser->>FileSystem: Read configuration file + FileSystem-->>ConfigParser: Configuration data + ConfigParser->>ConfigCache: Populate log level cache + ConfigCache-->>ConfigParser: Cache initialized + ConfigParser-->>RDKLogger: Configuration loaded + RDKLogger-->>App: RDK_SUCCESS (ready for logging) +``` + +## Implementation Details + +### Major HAL APIs Integration + +RDK Logger operates at the middleware layer and does not directly interface with Hardware Abstraction Layer (HAL) APIs. Instead, it provides logging services to RDK-B components that do interact with HAL layers. However, RDK Logger does integrate with system-level APIs for file access, network communication, and process management. + +**Core System APIs:** + +| System API | Purpose | Implementation File | +|---------|---------|-------------------| +| `socket()`, `bind()`, `recvfrom()` | UDP socket communication for runtime control via rdklogctrl | `src/rdk_dynamic_logger.c` | +| `fopen()`, `fread()`, `stat()` | Configuration file reading and monitoring | `src/rdk_logger_init.c`, `src/rdk_debug_priv.c` | +| `log4c_init()`, `log4c_category_log()` | Log4C backend initialization and message output | `src/rdk_debug_priv.c` | +| `gettimeofday()`, `localtime_r()` | Timestamp generation for log message formatting | `src/rdk_debug_priv.c` | +| `pthread_mutex_*()` | Thread synchronization for configuration updates | `src/rdk_logger_init.c`, `src/rdk_dynamic_logger.c` | + +### Key Implementation Logic + +- **Configuration Management Engine**: Core configuration system implemented in `src/rdk_logger_init.c` and `src/rdk_debug_priv.c` handles parsing of debug.ini files, detection of configuration overrides, and maintenance of in-memory configuration cache. The system supports three-tier configuration priority (`/opt/debug.ini`, `/nvram/debug.ini`, `/etc/debug.ini`) with automatic fallback mechanisms. + - Main configuration parsing logic in `rdk_logger_init()` and `rdk_dbg_priv_config()` functions + - Configuration override detection with three-tier priority file checking + - In-memory cache management with atomic updates for thread safety + +- **Dynamic Runtime Control**: Real-time log level modification system implemented in `src/rdk_dynamic_logger.c` provides UDP-based communication mechanism for the `rdklogctrl` utility. The system enables immediate log level changes without application restart. + - UDP server implementation for control message reception + - Message parsing and validation for security and stability + - Atomic configuration updates with immediate effect propagation + +- **Performance Optimization Strategy**: High-performance logging implementation optimizes the critical path for log message processing to minimize impact on client applications. + - Fast-path log level checking using atomic memory operations + - Compile-time optimization for disabled log levels through macro expansion + - Minimal function call overhead with inline level checks + - Efficient message formatting with pre-allocated buffers + +- **Error Handling and Resilience**: Comprehensive error handling ensures logging system availability even under adverse conditions. + - Configuration file parsing error recovery with fallback to default settings + - Log4C backend failure handling with automatic fallback to stdout/stderr + - Network communication error handling for runtime control operations + - Memory allocation failure handling with graceful degradation + +- **Logging & Debugging**: Multi-level internal diagnostics and debugging support for troubleshooting logging system issues. + - Internal debug logging with separate debug levels for RDK Logger itself + - Configuration validation and reporting mechanisms + - Runtime state monitoring and diagnostic output + - Performance metrics collection for optimization analysis + +### Key Configuration Files + +| Configuration File | Purpose | Override Mechanisms | +|--------------------|---------|--------------------| +| `/etc/debug.ini` | Default system-wide logging configuration with default log levels for all RDK-B components | Overridden by `/opt/debug.ini` or `/nvram/debug.ini` when present and readable | +| `/opt/debug.ini` | Platform-specific configuration override with highest priority | Takes precedence over all other configuration files when present and readable | +| `/nvram/debug.ini` | Runtime configuration override file for temporary or persistent log level changes | Takes precedence over `/etc/debug.ini` but lower priority than `/opt/debug.ini` | +| `log4crc` | Log4C backend configuration for output formatting, file rotation, and destination control | Log4C environment variables, application-specific log4crc files | +| `/var/log/messages` | Default log output destination for system-wide RDK-B component logs | Log4C configuration, syslog configuration, systemd journal settings | + diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md deleted file mode 100644 index 259fb52..0000000 --- a/docs/TROUBLESHOOTING.md +++ /dev/null @@ -1,514 +0,0 @@ -# RDK Logger Troubleshooting Guide - -## Common Issues and Solutions - -### 1. Logger Initialization Failures - -#### Issue: `rdk_logger_init()` returns error -**Symptoms:** -``` -Logger initialization failed with return: -1 -config_file ini is not found -``` - -**Causes and Solutions:** - -**Cause 1: Configuration file not found** -```bash -# Check if config file exists -ls -la /etc/debug.ini -ls -la /nvram/debug.ini -``` - -**Solution:** -```bash -# Create default configuration -sudo cp debug.ini.sample /etc/debug.ini -sudo chmod 644 /etc/debug.ini -``` - -**Cause 2: Permission issues** -```bash -# Check file permissions -ls -la /etc/debug.ini -``` - -**Solution:** -```bash -# Fix permissions -sudo chown root:root /etc/debug.ini -sudo chmod 644 /etc/debug.ini -``` - -**Cause 3: Invalid configuration format** -```ini -# Wrong format -INVALID.FORMAT=DEBUG - -# Correct format -LOG.RDK.MYAPP=DEBUG -``` - -#### Issue: Multiple initialization calls -**Problem:** -```c -// This can cause issues -RDK_LOGGER_INIT(); -RDK_LOGGER_INIT(); // Second call may fail -``` - -**Solution:** -```c -static int logger_initialized = 0; - -int init_logger_once() { - if (!logger_initialized) { - if (RDK_LOGGER_INIT() == RDK_SUCCESS) { - logger_initialized = 1; - return 0; - } - return -1; - } - return 0; // Already initialized -} -``` - -### 2. No Log Output - -#### Issue: Messages not appearing despite configuration - -**Debugging Steps:** - -**Step 1: Verify initialization** -```c -#include "rdk_logger.h" - -int main() { - printf("Before RDK_LOGGER_INIT\n"); - rdk_Error ret = RDK_LOGGER_INIT(); - printf("RDK_LOGGER_INIT returned: %d\n", ret); - - printf("Testing log output...\n"); - RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.TEST", "Test error message\n"); - RDK_LOG(RDK_LOG_INFO, "LOG.RDK.TEST", "Test info message\n"); - - rdk_logger_deinit(); - return 0; -} -``` - -**Step 2: Check configuration** -```bash -# Verify config file content -cat /etc/debug.ini - -# Check for your module -grep "LOG.RDK.TEST" /etc/debug.ini - -# Check default level -grep "LOG.RDK.DEFAULT" /etc/debug.ini -``` - -**Step 3: Test log level checking** -```c -// Debug log level checking -const char *module = "LOG.RDK.TEST"; -printf("ERROR enabled: %d\n", rdk_dbg_enabled(module, RDK_LOG_ERROR)); -printf("WARN enabled: %d\n", rdk_dbg_enabled(module, RDK_LOG_WARN)); -printf("INFO enabled: %d\n", rdk_dbg_enabled(module, RDK_LOG_INFO)); -printf("DEBUG enabled: %d\n", rdk_dbg_enabled(module, RDK_LOG_DEBUG)); -``` - -**Step 4: Check environment** -```bash -# Verify log4c is available -ldd your_application | grep log4c - -# Check if log4c config exists -find /etc -name "*log4c*" 2>/dev/null -``` - -### 3. Runtime Log Control Issues - -#### Issue: `rdklogctrl` not working - -**Problem:** Changes don't take effect -```bash -# Command appears to work but no change -rdklogctrl myapp LOG.RDK.NETWORK DEBUG -``` - -**Debugging:** - -**Step 1: Verify process name** -```bash -# Check exact process name -ps aux | grep myapp - -# Use exact name from ps output -rdklogctrl "myapp_process_name" LOG.RDK.NETWORK DEBUG -``` - -**Step 2: Check process accessibility** -```bash -# Verify process is running as expected user -ps -ef | grep myapp - -# Check if process accepts socket connections -netstat -tlnp | grep :12035 -``` - -**Step 3: Test with simple module** -```bash -# Try with a known module first -rdklogctrl myapp LOG.RDK.DEFAULT INFO -``` - -#### Issue: Dynamic logging not persistent -**Problem:** Log level changes revert after application restart - -**Explanation:** `rdklogctrl` changes are runtime-only. For persistent changes, modify `debug.ini`: - -```bash -# For persistent changes -sudo nano /etc/debug.ini - -# Add or modify -LOG.RDK.NETWORK=DEBUG -``` - -### 4. Performance Issues - -#### Issue: Logging causing performance degradation - -**Problem:** Application becomes slow when debug logging is enabled - -**Solution 1: Conditional logging** -```c -// Wrong - always evaluates expensive_function() -RDK_LOG(RDK_LOG_DEBUG, MODULE_NAME, "Debug: %s\n", expensive_function()); - -// Right - only calls expensive_function() if debug is enabled -if (rdk_dbg_enabled(MODULE_NAME, RDK_LOG_DEBUG)) { - RDK_LOG(RDK_LOG_DEBUG, MODULE_NAME, "Debug: %s\n", expensive_function()); -} -``` - -**Solution 2: Optimize log levels** -```ini -# Production config - minimal logging -LOG.RDK.DEFAULT=ERROR -LOG.RDK.CRITICAL_MODULE=WARN - -# Only enable debug for specific investigation -LOG.RDK.PROBLEM_MODULE=DEBUG -``` - -**Solution 3: Measure logging overhead** -```c -#include - -void measure_logging_performance() { - clock_t start = clock(); - - for (int i = 0; i < 10000; i++) { - RDK_LOG(RDK_LOG_INFO, "LOG.RDK.PERF", "Test message %d\n", i); - } - - clock_t end = clock(); - double time_spent = ((double)(end - start)) / CLOCKS_PER_SEC; - - printf("10000 log messages took %f seconds\n", time_spent); -} -``` - -### 5. Memory Issues - -#### Issue: Memory leaks or crashes - -**Problem:** Application crashes or shows memory leaks related to logging - -**Solution 1: Proper cleanup** -```c -#include - -void cleanup_handler(int sig) { - RDK_LOG(RDK_LOG_NOTICE, "LOG.RDK.MAIN", "Received signal %d, cleaning up\n", sig); - rdk_logger_deinit(); - exit(0); -} - -int main() { - // Register signal handlers - signal(SIGTERM, cleanup_handler); - signal(SIGINT, cleanup_handler); - - RDK_LOGGER_INIT(); - - // Application logic... - - rdk_logger_deinit(); - return 0; -} -``` - -**Solution 2: Check for double-free issues** -```c -// Avoid static string modification -char buffer[256]; -snprintf(buffer, sizeof(buffer), "Dynamic message: %d", value); -RDK_LOG(RDK_LOG_INFO, MODULE_NAME, "%s\n", buffer); -``` - -**Solution 3: Valgrind debugging** -```bash -# Run with valgrind to detect memory issues -valgrind --leak-check=full --show-leak-kinds=all ./your_app - -# Look for leaks in librdkloggers or liblog4c -``` - -### 6. Multi-threading Issues - -#### Issue: Garbled log output or crashes in multi-threaded applications - -**Problem:** Multiple threads logging simultaneously causing corruption - -**Solution 1: RDK Logger is thread-safe (internal synchronization)** -```c -#include - -void* worker_thread(void* arg) { - int thread_id = *(int*)arg; - - // This is safe - RDK Logger handles synchronization - RDK_LOG(RDK_LOG_INFO, "LOG.RDK.WORKER", - "Thread %d: Starting work\n", thread_id); - - // Do work... - - RDK_LOG(RDK_LOG_INFO, "LOG.RDK.WORKER", - "Thread %d: Work completed\n", thread_id); - - return NULL; -} -``` - -**Solution 2: If issues persist, add application-level synchronization** -```c -#include - -static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER; - -#define SAFE_LOG(level, module, format, ...) do { \ - pthread_mutex_lock(&log_mutex); \ - RDK_LOG(level, module, format, ##__VA_ARGS__); \ - pthread_mutex_unlock(&log_mutex); \ -} while(0) -``` - -### 7. Configuration Issues - -#### Issue: Module-specific settings not working - -**Problem:** Settings in debug.ini not taking effect for specific modules - -**Debug steps:** - -**Step 1: Verify module name format** -```ini -# Wrong formats -MYAPP=DEBUG # Missing LOG.RDK prefix -LOG.RDK.MyApp=DEBUG # Case sensitive -LOG.RDK. MYAPP=DEBUG # Extra space - -# Correct format -LOG.RDK.MYAPP=DEBUG -``` - -**Step 2: Check for syntax errors** -```bash -# Validate config file syntax -grep -n "=" /etc/debug.ini | grep -v "^#" - -# Check for invalid characters -hexdump -C /etc/debug.ini | head -20 -``` - -**Step 3: Test with minimal config** -```ini -# Minimal test config -LOG.RDK.DEFAULT=INFO -LOG.RDK.TEST=DEBUG -``` - -#### Issue: Case sensitivity problems - -**Problem:** Module names not matching due to case differences - -```c -// These are different modules -RDK_LOG(RDK_LOG_INFO, "LOG.RDK.MyApp", "Message\n"); // MyApp -RDK_LOG(RDK_LOG_INFO, "LOG.RDK.MYAPP", "Message\n"); // MYAPP -RDK_LOG(RDK_LOG_INFO, "LOG.RDK.myapp", "Message\n"); // myapp -``` - -**Solution:** Use consistent naming convention -```c -// Define module name once -#define MODULE_NAME "LOG.RDK.MYAPP" - -// Use throughout application -RDK_LOG(RDK_LOG_INFO, MODULE_NAME, "Message\n"); -``` - -### 8. Build and Linking Issues - -#### Issue: Undefined references during compilation - -**Problem:** -``` -undefined reference to `rdk_logger_init' -undefined reference to `rdk_logger_msg_printf' -``` - -**Solution 1: Check linking order** -```bash -# Wrong order -gcc -lrdkloggers myapp.c -llog4c -lglib-2.0 - -# Correct order -gcc myapp.c -lrdkloggers -llog4c -lglib-2.0 -``` - -**Solution 2: Verify library installation** -```bash -# Check if libraries are installed -ldconfig -p | grep rdkloggers -ldconfig -p | grep log4c - -# Find library files -find /usr -name "librdkloggers*" 2>/dev/null -find /usr -name "liblog4c*" 2>/dev/null -``` - -**Solution 3: Use pkg-config if available** -```bash -# Check for pkg-config files -pkg-config --list-all | grep rdk - -# If available, use pkg-config -gcc myapp.c `pkg-config --cflags --libs rdklogger` -``` - -### 9. Log File Issues - -#### Issue: Log files not being created or rotated - -**Problem:** Using `rdk_logger_ext_init()` but files not appearing - -**Debug steps:** - -**Step 1: Check directory permissions** -```c -rdk_logger_ext_config_t config = { - .fileName = "myapp.log", - .logdir = "/var/log/", // Check if writable - .maxSize = 1024 * 1024, - .maxCount = 5 -}; - -// Test directory access -if (access("/var/log/", W_OK) != 0) { - perror("Cannot write to /var/log/"); -} -``` - -**Step 2: Use accessible directory** -```c -rdk_logger_ext_config_t config = { - .fileName = "myapp.log", - .logdir = "/tmp/", // Use /tmp for testing - .maxSize = 1024 * 1024, - .maxCount = 5 -}; -``` - -**Step 3: Check log4c configuration** -```bash -# Look for log4c config files -find /etc -name "*log4c*" 2>/dev/null - -# Check log4c configuration -export LOG4C_APPENDER_FILE_FILENAME="/tmp/test.log" -./your_app -``` - -### 10. Debugging Tools and Techniques - -#### Environment Variables -```bash -# Enable log4c debugging -export LOG4C_PRIORITY=debug -export LOG4C_APPENDER=stdout - -# Run your application -./your_app -``` - -#### Debugging Configuration Loading -```c -#include "rdk_logger.h" - -void debug_config_loading() { - printf("Checking config files:\n"); - - // Check primary config - if (access("/etc/debug.ini", F_OK) == 0) { - printf("✓ /etc/debug.ini exists\n"); - } else { - printf("✗ /etc/debug.ini not found\n"); - } - - // Check override config - if (access("/nvram/debug.ini", F_OK) == 0) { - printf("✓ /nvram/debug.ini exists (will be used)\n"); - } else { - printf("✗ /nvram/debug.ini not found\n"); - } - - // Test initialization - rdk_Error ret = RDK_LOGGER_INIT(); - printf("Logger init result: %d (%s)\n", ret, - ret == RDK_SUCCESS ? "SUCCESS" : "FAILED"); -} -``` - -#### Network Debugging for rdklogctrl -```bash -# Check if dynamic logger port is listening -netstat -tlnp | grep :12035 - -# Test socket connection -telnet localhost 12035 - -# Monitor network traffic -tcpdump -i lo port 12035 -``` - -### Quick Reference Checklist - -When troubleshooting RDK Logger issues: - -1. **✓ Check configuration file exists and is readable** -2. **✓ Verify module names follow LOG.RDK.* convention** -3. **✓ Confirm logger initialization succeeded** -4. **✓ Test with simple log levels (ERROR, INFO)** -5. **✓ Check process name for rdklogctrl commands** -6. **✓ Verify library linking is correct** -7. **✓ Test with minimal configuration** -8. **✓ Check file permissions for log directories** -9. **✓ Use debugging tools (valgrind, gdb, strace)** -10. **✓ Enable log4c debugging if needed** - -This troubleshooting guide should help resolve most common issues with RDK Logger implementation and usage. \ No newline at end of file