CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyrealsense2

Python bindings for Intel RealSense SDK 2.0 providing access to depth and color cameras for computer vision applications.

Pending
Overview
Eval results
Files

logging.mddocs/

Logging & Diagnostics

Global logging system for debugging and diagnostics, providing flexible output control with support for console output, file logging, and custom callback functions. Enables comprehensive debugging of RealSense operations and device communication.

Capabilities

Logging Configuration

Global logging setup and control functions.

def log_to_console(severity):
    """
    Enable logging to console output.
    
    Args:
        severity (log_severity): Minimum severity level to log
    """

def log_to_file(severity, file_path):
    """
    Enable logging to file.
    
    Args:
        severity (log_severity): Minimum severity level to log
        file_path (str): Path to log file
    """

def log_to_callback(severity, callback_function):
    """
    Enable logging to custom callback function.
    
    Args:
        severity (log_severity): Minimum severity level to log
        callback_function: Function called with log messages
    """

def enable_rolling_log_file(severity, file_path, max_size):
    """
    Enable rolling log file with size limit.
    
    Args:
        severity (log_severity): Minimum severity level to log
        file_path (str): Base path for log files
        max_size (int): Maximum file size in bytes before rolling
    """

def reset_logger():
    """Reset logger configuration to default state."""

def log(severity, message):
    """
    Log a message at specified severity level.
    
    Args:
        severity (log_severity): Message severity level
        message (str): Message to log
    """

Log Message Structure

Log message data structure for custom callback processing.

class log_message:
    def __init__(severity, message, filename, line_number):
        """
        Create log message.
        
        Args:
            severity (log_severity): Message severity
            message (str): Log message content
            filename (str): Source file name
            line_number (int): Source line number
        """
    
    def get_severity() -> log_severity:
        """
        Get message severity level.
        
        Returns:
            log_severity: Severity level
        """
    
    def get_message() -> str:
        """
        Get log message content.
        
        Returns:
            str: Message text
        """
    
    def get_filename() -> str:
        """
        Get source filename.
        
        Returns:
            str: Source file name
        """
    
    def get_line_number() -> int:
        """
        Get source line number.
        
        Returns:
            int: Line number in source file
        """

Severity Levels

Log severity enumeration for filtering messages.

# Log severity levels (from lowest to highest)
rs.log_severity.debug    # Detailed debugging information
rs.log_severity.info     # General informational messages  
rs.log_severity.warn     # Warning conditions
rs.log_severity.error    # Error conditions
rs.log_severity.fatal    # Fatal error conditions
rs.log_severity.none     # Disable all logging

Usage Examples

Console Logging

import pyrealsense2 as rs

# Enable debug-level console logging
rs.log_to_console(rs.log_severity.debug)

# Now all RealSense operations will log to console
pipeline = rs.pipeline()
profile = pipeline.start()

# This will generate log output about device initialization
frames = pipeline.wait_for_frames()

pipeline.stop()

File Logging

import pyrealsense2 as rs
import os

# Enable logging to file
log_file = "realsense_debug.log"
rs.log_to_file(rs.log_severity.info, log_file)

try:
    # RealSense operations with file logging
    ctx = rs.context()
    devices = ctx.query_devices()
    
    for device in devices:
        print(f"Device: {device.get_info(rs.camera_info.name)}")
        
    # Check log file
    if os.path.exists(log_file):
        with open(log_file, 'r') as f:
            log_content = f.read()
            print(f"\nLog file contains {len(log_content)} characters")
            
finally:
    # Reset logging to avoid affecting other operations
    rs.reset_logger()

Rolling Log Files

import pyrealsense2 as rs

# Enable rolling log files (1MB max size)
rs.enable_rolling_log_file(
    rs.log_severity.warn, 
    "realsense_rolling.log", 
    1024 * 1024  # 1MB
)

# Long-running application
pipeline = rs.pipeline()
profile = pipeline.start()

try:
    for i in range(10000):
        frames = pipeline.wait_for_frames()
        # Process frames...
        
finally:
    pipeline.stop()
    rs.reset_logger()

Custom Logging Callback

import pyrealsense2 as rs
from datetime import datetime

def custom_log_callback(message):
    """Custom logging callback with timestamp formatting."""
    severity = message.get_severity()
    content = message.get_message()
    filename = message.get_filename()
    line_num = message.get_line_number()
    
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
    severity_name = severity.name.upper()
    
    # Custom log format
    log_line = f"[{timestamp}] {severity_name:5} {filename}:{line_num} - {content}"
    
    # Write to custom destination (database, network, etc.)
    print(log_line)
    
    # Could also write to database, send to remote logging service, etc.

# Set up custom logging
rs.log_to_callback(rs.log_severity.debug, custom_log_callback)

# RealSense operations will now use custom callback
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)

try:
    profile = pipeline.start(config)
    
    for frame_count in range(100):
        frames = pipeline.wait_for_frames()
        depth = frames.get_depth_frame()
        if depth:
            # This will generate log messages processed by custom callback
            center_distance = depth.get_distance(320, 240)
            
finally:
    pipeline.stop()
    rs.reset_logger()

Manual Logging

import pyrealsense2 as rs

# Set up logging destination
rs.log_to_console(rs.log_severity.debug)

# Manual log messages
rs.log(rs.log_severity.info, "Application starting up")
rs.log(rs.log_severity.debug, "Initializing RealSense context")

try:
    ctx = rs.context()
    devices = ctx.query_devices()
    
    rs.log(rs.log_severity.info, f"Found {len(devices)} devices")
    
    for i, device in enumerate(devices):
        serial = device.get_info(rs.camera_info.serial_number)
        rs.log(rs.log_severity.debug, f"Device {i}: {serial}")
        
except Exception as e:
    rs.log(rs.log_severity.error, f"Error during device discovery: {e}")
    
finally:
    rs.log(rs.log_severity.info, "Application shutting down")
    rs.reset_logger()

Conditional Logging

import pyrealsense2 as rs

def setup_logging_for_debug_mode(debug_enabled=False):
    """Configure logging based on debug mode."""
    rs.reset_logger()  # Clear any existing configuration
    
    if debug_enabled:
        # Verbose logging for debugging
        rs.log_to_console(rs.log_severity.debug)
        rs.log_to_file(rs.log_severity.debug, "debug.log")
        print("Debug logging enabled")
    else:
        # Minimal logging for production
        rs.log_to_file(rs.log_severity.error, "errors.log")
        print("Production logging enabled")

# Example usage
DEBUG_MODE = True  # Could be from command line args, config file, etc.

setup_logging_for_debug_mode(DEBUG_MODE)

try:
    # Application code
    pipeline = rs.pipeline()
    profile = pipeline.start()
    
    # This will log differently based on debug mode
    frames = pipeline.wait_for_frames()
    
finally:
    pipeline.stop()
    rs.reset_logger()

Integration with Python Logging

import pyrealsense2 as rs
import logging

# Set up Python logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('application.log'),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger(__name__)

def realsense_to_python_log(rs_message):
    """Bridge RealSense logging to Python logging."""
    severity = rs_message.get_severity()
    message = rs_message.get_message()
    filename = rs_message.get_filename()
    line_num = rs_message.get_line_number()
    
    # Format message with source information
    formatted_msg = f"{filename}:{line_num} - {message}"
    
    # Map RealSense severity to Python logging levels
    if severity == rs.log_severity.debug:
        logger.debug(formatted_msg)
    elif severity == rs.log_severity.info:
        logger.info(formatted_msg)
    elif severity == rs.log_severity.warn:
        logger.warning(formatted_msg)
    elif severity == rs.log_severity.error:
        logger.error(formatted_msg)
    elif severity == rs.log_severity.fatal:
        logger.critical(formatted_msg)

# Connect RealSense logging to Python logging
rs.log_to_callback(rs.log_severity.debug, realsense_to_python_log)

# Now RealSense logs will appear in Python logging system
logger.info("Starting RealSense application")

try:
    pipeline = rs.pipeline()
    profile = pipeline.start()
    
    frames = pipeline.wait_for_frames()
    logger.info("Successfully captured frames")
    
finally:
    pipeline.stop()
    logger.info("RealSense pipeline stopped")
    rs.reset_logger()

Performance Considerations

  • Logging Overhead: Verbose logging can impact performance, especially at debug level
  • File I/O: File logging adds disk I/O overhead; consider using rolling logs for long-running applications
  • Memory Usage: Log callbacks should process messages quickly to avoid memory buildup
  • Thread Safety: Logging functions are thread-safe and can be called from frame callbacks

Best Practices

  • Reset Logger: Always call rs.reset_logger() when done to avoid affecting other applications
  • Appropriate Levels: Use appropriate severity levels - debug for development, warn/error for production
  • File Management: Monitor log file sizes and implement rotation for long-running applications
  • Custom Callbacks: Keep callback functions lightweight to avoid impacting performance
  • Error Handling: Wrap logging setup in try-catch blocks to handle file permission issues

Install with Tessl CLI

npx tessl i tessl/pypi-pyrealsense2

docs

advanced-mode.md

context-device.md

frames.md

index.md

logging.md

options.md

pipeline.md

pointclouds.md

processing.md

recording.md

sensors.md

tile.json