Last active
July 11, 2024 13:28
-
-
Save ablakey/4f57dca4ea75ed29c49ff00edf622b38 to your computer and use it in GitHub Desktop.
Fixing broken logging after rospy.init_node()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import rospy | |
class ConnectPythonLoggingToROS(logging.Handler): | |
level_map = { | |
logging.DEBUG: rospy.logdebug, | |
logging.INFO: rospy.loginfo, | |
logging.WARNING: rospy.logwarn, | |
logging.ERROR: rospy.logerr, | |
logging.CRITICAL: rospy.logfatal | |
} | |
def emit(self, record): | |
try: | |
self.level_map[record.levelno]("%s: %s" % (record.name, record.msg)) | |
except KeyError: | |
rospy.logerr("unknown log level %s LOG: %s: %s" % (record.levelno, record.name, record.msg)) | |
def route_logger_to_ros(logger_name): | |
'''Re-routes a Python logging.logger to the ROS logging infrastructure. | |
Without using this, once `rospy.init_node()` has been called, any use of `logging` occurs silently. | |
Example: | |
rospy.init_node('my_node') | |
route_logger_to_ros('my_custom_library') | |
# In an imported library: | |
logger = logging.getLogger('my_custom_library) | |
logger.info('This message gets routed to ROS logging if a ROS node was initialized in this process.') | |
''' | |
logging.getLogger(logger_name).addHandler(ConnectPythonLoggingToROS()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
errors :
(venv3.9) ucar@superbrain:~/ucar_ws/src/ucar_camera/src$ rosrun ucar_camera iflydetect(复件).py
An error occurred: Unknown level: 'DEBUG'
Traceback (most recent call last):
File "/home/ucar/ucar_ws/src/ucar_camera/src/iflydetect(复件).py", line 229, in
rospy.init_node("cv_bridge_test")
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/client.py", line 309, in init_node
rospy.core.configure_logging(resolved_node_name)
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/core.py", line 405, in configure_logging
_log_filename = rosgraph.roslogging.configure_logging('rospy', level, filename=filename)
File "/opt/ros/noetic/lib/python3/dist-packages/rosgraph/roslogging.py", line 192, in configure_logging
logging.config.fileConfig(config_file, disable_existing_loggers=False)
File "/usr/local/python3.9/lib/python3.9/logging/config.py", line 79, in fileConfig
handlers = _install_handlers(cp, formatters)
File "/usr/local/python3.9/lib/python3.9/logging/config.py", line 149, in _install_handlers
h.setLevel(level)
File "/usr/local/python3.9/lib/python3.9/logging/init.py", line 910, in setLevel
self.level = _checkLevel(level)
File "/usr/local/python3.9/lib/python3.9/logging/init.py", line 194, in _checkLevel
raise ValueError("Unknown level: %r" % level)
ValueError: Unknown level: 'DEBUG'