Skip to content

Commit

Permalink
add logging handler to log ROS2 as well
Browse files Browse the repository at this point in the history
Signed-off-by: Daisuke Sato <[email protected]>
  • Loading branch information
daisukes committed Feb 27, 2024
1 parent 73fc223 commit d579829
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions cabot_navigation2/test/run_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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="""
Expand Down Expand Up @@ -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)

Expand Down

0 comments on commit d579829

Please sign in to comment.