or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-mode.mdcontext-device.mdframes.mdindex.mdlogging.mdoptions.mdpipeline.mdpointclouds.mdprocessing.mdrecording.mdsensors.md

logging.mddocs/

0

# Logging & Diagnostics

1

2

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.

3

4

## Capabilities

5

6

### Logging Configuration

7

8

Global logging setup and control functions.

9

10

```python { .api }

11

def log_to_console(severity):

12

"""

13

Enable logging to console output.

14

15

Args:

16

severity (log_severity): Minimum severity level to log

17

"""

18

19

def log_to_file(severity, file_path):

20

"""

21

Enable logging to file.

22

23

Args:

24

severity (log_severity): Minimum severity level to log

25

file_path (str): Path to log file

26

"""

27

28

def log_to_callback(severity, callback_function):

29

"""

30

Enable logging to custom callback function.

31

32

Args:

33

severity (log_severity): Minimum severity level to log

34

callback_function: Function called with log messages

35

"""

36

37

def enable_rolling_log_file(severity, file_path, max_size):

38

"""

39

Enable rolling log file with size limit.

40

41

Args:

42

severity (log_severity): Minimum severity level to log

43

file_path (str): Base path for log files

44

max_size (int): Maximum file size in bytes before rolling

45

"""

46

47

def reset_logger():

48

"""Reset logger configuration to default state."""

49

50

def log(severity, message):

51

"""

52

Log a message at specified severity level.

53

54

Args:

55

severity (log_severity): Message severity level

56

message (str): Message to log

57

"""

58

```

59

60

### Log Message Structure

61

62

Log message data structure for custom callback processing.

63

64

```python { .api }

65

class log_message:

66

def __init__(severity, message, filename, line_number):

67

"""

68

Create log message.

69

70

Args:

71

severity (log_severity): Message severity

72

message (str): Log message content

73

filename (str): Source file name

74

line_number (int): Source line number

75

"""

76

77

def get_severity() -> log_severity:

78

"""

79

Get message severity level.

80

81

Returns:

82

log_severity: Severity level

83

"""

84

85

def get_message() -> str:

86

"""

87

Get log message content.

88

89

Returns:

90

str: Message text

91

"""

92

93

def get_filename() -> str:

94

"""

95

Get source filename.

96

97

Returns:

98

str: Source file name

99

"""

100

101

def get_line_number() -> int:

102

"""

103

Get source line number.

104

105

Returns:

106

int: Line number in source file

107

"""

108

```

109

110

### Severity Levels

111

112

Log severity enumeration for filtering messages.

113

114

```python { .api }

115

# Log severity levels (from lowest to highest)

116

rs.log_severity.debug # Detailed debugging information

117

rs.log_severity.info # General informational messages

118

rs.log_severity.warn # Warning conditions

119

rs.log_severity.error # Error conditions

120

rs.log_severity.fatal # Fatal error conditions

121

rs.log_severity.none # Disable all logging

122

```

123

124

## Usage Examples

125

126

### Console Logging

127

128

```python

129

import pyrealsense2 as rs

130

131

# Enable debug-level console logging

132

rs.log_to_console(rs.log_severity.debug)

133

134

# Now all RealSense operations will log to console

135

pipeline = rs.pipeline()

136

profile = pipeline.start()

137

138

# This will generate log output about device initialization

139

frames = pipeline.wait_for_frames()

140

141

pipeline.stop()

142

```

143

144

### File Logging

145

146

```python

147

import pyrealsense2 as rs

148

import os

149

150

# Enable logging to file

151

log_file = "realsense_debug.log"

152

rs.log_to_file(rs.log_severity.info, log_file)

153

154

try:

155

# RealSense operations with file logging

156

ctx = rs.context()

157

devices = ctx.query_devices()

158

159

for device in devices:

160

print(f"Device: {device.get_info(rs.camera_info.name)}")

161

162

# Check log file

163

if os.path.exists(log_file):

164

with open(log_file, 'r') as f:

165

log_content = f.read()

166

print(f"\nLog file contains {len(log_content)} characters")

167

168

finally:

169

# Reset logging to avoid affecting other operations

170

rs.reset_logger()

171

```

172

173

### Rolling Log Files

174

175

```python

176

import pyrealsense2 as rs

177

178

# Enable rolling log files (1MB max size)

179

rs.enable_rolling_log_file(

180

rs.log_severity.warn,

181

"realsense_rolling.log",

182

1024 * 1024 # 1MB

183

)

184

185

# Long-running application

186

pipeline = rs.pipeline()

187

profile = pipeline.start()

188

189

try:

190

for i in range(10000):

191

frames = pipeline.wait_for_frames()

192

# Process frames...

193

194

finally:

195

pipeline.stop()

196

rs.reset_logger()

197

```

198

199

### Custom Logging Callback

200

201

```python

202

import pyrealsense2 as rs

203

from datetime import datetime

204

205

def custom_log_callback(message):

206

"""Custom logging callback with timestamp formatting."""

207

severity = message.get_severity()

208

content = message.get_message()

209

filename = message.get_filename()

210

line_num = message.get_line_number()

211

212

timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]

213

severity_name = severity.name.upper()

214

215

# Custom log format

216

log_line = f"[{timestamp}] {severity_name:5} {filename}:{line_num} - {content}"

217

218

# Write to custom destination (database, network, etc.)

219

print(log_line)

220

221

# Could also write to database, send to remote logging service, etc.

222

223

# Set up custom logging

224

rs.log_to_callback(rs.log_severity.debug, custom_log_callback)

225

226

# RealSense operations will now use custom callback

227

pipeline = rs.pipeline()

228

config = rs.config()

229

config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)

230

231

try:

232

profile = pipeline.start(config)

233

234

for frame_count in range(100):

235

frames = pipeline.wait_for_frames()

236

depth = frames.get_depth_frame()

237

if depth:

238

# This will generate log messages processed by custom callback

239

center_distance = depth.get_distance(320, 240)

240

241

finally:

242

pipeline.stop()

243

rs.reset_logger()

244

```

245

246

### Manual Logging

247

248

```python

249

import pyrealsense2 as rs

250

251

# Set up logging destination

252

rs.log_to_console(rs.log_severity.debug)

253

254

# Manual log messages

255

rs.log(rs.log_severity.info, "Application starting up")

256

rs.log(rs.log_severity.debug, "Initializing RealSense context")

257

258

try:

259

ctx = rs.context()

260

devices = ctx.query_devices()

261

262

rs.log(rs.log_severity.info, f"Found {len(devices)} devices")

263

264

for i, device in enumerate(devices):

265

serial = device.get_info(rs.camera_info.serial_number)

266

rs.log(rs.log_severity.debug, f"Device {i}: {serial}")

267

268

except Exception as e:

269

rs.log(rs.log_severity.error, f"Error during device discovery: {e}")

270

271

finally:

272

rs.log(rs.log_severity.info, "Application shutting down")

273

rs.reset_logger()

274

```

275

276

### Conditional Logging

277

278

```python

279

import pyrealsense2 as rs

280

281

def setup_logging_for_debug_mode(debug_enabled=False):

282

"""Configure logging based on debug mode."""

283

rs.reset_logger() # Clear any existing configuration

284

285

if debug_enabled:

286

# Verbose logging for debugging

287

rs.log_to_console(rs.log_severity.debug)

288

rs.log_to_file(rs.log_severity.debug, "debug.log")

289

print("Debug logging enabled")

290

else:

291

# Minimal logging for production

292

rs.log_to_file(rs.log_severity.error, "errors.log")

293

print("Production logging enabled")

294

295

# Example usage

296

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

297

298

setup_logging_for_debug_mode(DEBUG_MODE)

299

300

try:

301

# Application code

302

pipeline = rs.pipeline()

303

profile = pipeline.start()

304

305

# This will log differently based on debug mode

306

frames = pipeline.wait_for_frames()

307

308

finally:

309

pipeline.stop()

310

rs.reset_logger()

311

```

312

313

## Integration with Python Logging

314

315

```python

316

import pyrealsense2 as rs

317

import logging

318

319

# Set up Python logging

320

logging.basicConfig(

321

level=logging.DEBUG,

322

format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',

323

handlers=[

324

logging.FileHandler('application.log'),

325

logging.StreamHandler()

326

]

327

)

328

329

logger = logging.getLogger(__name__)

330

331

def realsense_to_python_log(rs_message):

332

"""Bridge RealSense logging to Python logging."""

333

severity = rs_message.get_severity()

334

message = rs_message.get_message()

335

filename = rs_message.get_filename()

336

line_num = rs_message.get_line_number()

337

338

# Format message with source information

339

formatted_msg = f"{filename}:{line_num} - {message}"

340

341

# Map RealSense severity to Python logging levels

342

if severity == rs.log_severity.debug:

343

logger.debug(formatted_msg)

344

elif severity == rs.log_severity.info:

345

logger.info(formatted_msg)

346

elif severity == rs.log_severity.warn:

347

logger.warning(formatted_msg)

348

elif severity == rs.log_severity.error:

349

logger.error(formatted_msg)

350

elif severity == rs.log_severity.fatal:

351

logger.critical(formatted_msg)

352

353

# Connect RealSense logging to Python logging

354

rs.log_to_callback(rs.log_severity.debug, realsense_to_python_log)

355

356

# Now RealSense logs will appear in Python logging system

357

logger.info("Starting RealSense application")

358

359

try:

360

pipeline = rs.pipeline()

361

profile = pipeline.start()

362

363

frames = pipeline.wait_for_frames()

364

logger.info("Successfully captured frames")

365

366

finally:

367

pipeline.stop()

368

logger.info("RealSense pipeline stopped")

369

rs.reset_logger()

370

```

371

372

## Performance Considerations

373

374

- **Logging Overhead**: Verbose logging can impact performance, especially at debug level

375

- **File I/O**: File logging adds disk I/O overhead; consider using rolling logs for long-running applications

376

- **Memory Usage**: Log callbacks should process messages quickly to avoid memory buildup

377

- **Thread Safety**: Logging functions are thread-safe and can be called from frame callbacks

378

379

## Best Practices

380

381

- **Reset Logger**: Always call `rs.reset_logger()` when done to avoid affecting other applications

382

- **Appropriate Levels**: Use appropriate severity levels - debug for development, warn/error for production

383

- **File Management**: Monitor log file sizes and implement rotation for long-running applications

384

- **Custom Callbacks**: Keep callback functions lightweight to avoid impacting performance

385

- **Error Handling**: Wrap logging setup in try-catch blocks to handle file permission issues