From d579829a675fb61c0840e3c2adc5028043eb031e Mon Sep 17 00:00:00 2001 From: Daisuke Sato Date: Tue, 27 Feb 2024 00:03:42 -0500 Subject: [PATCH] add logging handler to log ROS2 as well Signed-off-by: Daisuke Sato --- cabot_navigation2/test/run_test.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/cabot_navigation2/test/run_test.py b/cabot_navigation2/test/run_test.py index 4f889f88..a22aa33e 100755 --- a/cabot_navigation2/test/run_test.py +++ b/cabot_navigation2/test/run_test.py @@ -625,6 +625,29 @@ def format(self, record): return formatter.format(record) +class ROS2LogHandler(logging.Handler): + """A logging handler that forwards Python logging messages to ROS2 logging.""" + + def __init__(self, node: rclpy.node.Node): + super().__init__() + self.node = node + + def emit(self, record): + """Override emit to forward the log message to ROS2 logging.""" + msg = self.format(record) + level = record.levelno + if level >= logging.CRITICAL: + self.node.get_logger().fatal(msg) + elif level >= logging.ERROR: + self.node.get_logger().error(msg) + elif level >= logging.WARNING: + self.node.get_logger().warn(msg) + elif level >= logging.INFO: + self.node.get_logger().info(msg) + else: # DEBUG and NOTSET + self.node.get_logger().debug(msg) + + def main(): global node, manager, logger parser = OptionParser(usage=""" @@ -654,6 +677,9 @@ def main(): node = rclpy.node.Node("test_node") manager = PedestrianManager(node) + ros2Handler = ROS2LogHandler(node) + logger.addHandler(ros2Handler) + evaluator = Evaluator(node) evaluator.set_logger(logger)