Skip to content

Logging interoperability

mhidalgo-bdai edited this page Oct 31, 2023 · 1 revision

To facilitate logging, bdai_ros2_wrappers include functionality to bridge code using Python standard logging with the ROS 2 logging system.

API review

Standard logging

import logging

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.info("Logged using standard logging")

These logs will be handled by Python's standard logging module (i.e. printed to console).

Standalone rclpy logging

import rclpy.logging

logger = rclpy.logging.get_logger(__name__)
logger.set_level(rclpy.logging.LoggingSeverity.INFO)
logger.info("Logged using a standalone rclpy logger")

These logs will be ultimately handled by rcutils logging system (i.e. printed to console, perhaps forwarded to spdlog).

rclpy node logging

import rclpy
import rclpy.logging

node = rclpy.create_node("my_node")
logger = node.get_logger()
logger.set_level(rclpy.logging.LoggingSeverity.INFO)
logger.info("Logged using an rclpy node logger")

These logs will be ultimately handled by rcutils logging system too, but will also be published to /rosout.

Log bridging

Managing multiple, independent logging systems is impractical. So is reworking a codebase to accommodate either. To avoid both scenarios, use bdai_ros2_wrappers.logging.logs_to_ros explicitly:

import logging
import rclpy

from bdai_ros2_wrappers.logging import logs_to_ros

node = rclpy.create_node("my_node")
with logs_to_ros(node):
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)
    logger.info("Logged using standard logging")

or implicitly through process-wide APIs:

import logging

from bdai_ros2_wrappers.process as ros_process

@ros_process.main()
def main():
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)
    logger.info("Logged using standard logging")

if __name__ == "__main__":
    main()    

logging logs will propagate up the logger hierarchy and then forwarded to the logger of the corresponding node (the one provided in the first case, or the main prebaked node in the second case) and thus at least printed to console and published to /rosout. Note the above presumes that severity levels at every step of the way are such that the corresponding log will get through (in this example, INFO or below for both logging and ROS 2 logging system).