I'm trying to convert some code from ros1 into ros2. In ros1, it was possible to print logging messages from anywhere in a process by using rospy.loginfo("my_message") once a node was initialised.
In ros2 things work differently, and the logger is attached to a node and is retrieved with the node.get_logger() function. However, this is sometimes inconvenient, because accessing that logger would require passing the node object around to a variety of other objects which shouldn't care about the node. These objects might be used multiple times in different parts of the system.
I found this question Global logger for logging without a node which indicates that you can do something like
import rclpy
from rclpy.impl import rcutils_logger
from rclpy.node import Node
if __name__ == "__main__":
rclpy.init()
my_node = Node("my_node")
my_node.get_logger().info("Did something")
rcutils_logger.RcutilsLogger(name="temp_logger").info("Non-ros component message")
This does work, but results in logs like
[INFO] [1738333789.963975903] [my_node]: Did something
[INFO] [1738333789.964233143] [temp_logger]: Non-ros component message
where the message from the rcutils logger appears from a different logger than the one from the node, since we specify a different name. This could be a problem if we're using this non-ros component in multiple different places, since we don't know which node the message is actually coming from.
In this tiny example we could just call the temporary logger a different name, but in practice that wouldn't work since we don't know what node we're actually in when creating the logger. Perhaps there are two possible options here:
- Retrieve the logger for the node in some way which doesn't require ros interaction. Perhaps through the logging api?
- Get the correct name for the node and instantiate the logger that way. But this probably requires ros interaction to get node names.
I would appreciate any suggestions for approaches to logging without access to a node, which would appear in the ROS logs.