Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reconnect python logging calls with the ROS logging system
class ConnectPythonLoggingToROS(logging.Handler):
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.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))
#reconnect logging calls which are children of this to the ros log system
logging.getLogger('trigger').addHandler(ConnectPythonLoggingToROS())
#logs sent to children of trigger with a level >= this will be redirected to ROS
logging.getLogger('trigger').setLevel(logging.DEBUG)
rospy.init_node('triggerbox_host', log_level=rospy.DEBUG)
@dogoepp

This comment has been minimized.

Copy link

commented Sep 1, 2016

Thanks a lot for this snippet ! It's perfect :)

@BoltzmannBrain

This comment has been minimized.

Copy link

commented Oct 19, 2017

This is cool, thanks for posting! Do you have this in the context of an example though? I have a few specific questions:

a. Do you still call rospy.loginfo("my message") in your code, or do you use the Python logger (below)?

import logging
LOG = logging.getlogger(__name__)
LOG.info("my message")

b. Is there a way you can have this defined once in the repo such that each module can just import MyCoolLogger and use it generically?

Basically I'm looking to implement a custom logger that invokes rospy logging in the ROS pieces of my codebase, but uses the Python system logger elsewhere.

@felixdivo

This comment has been minimized.

Copy link

commented Dec 22, 2017

I use

self.MAP[record.levelno]("%s: %s" % (record.name, record.getMessage()))

instead of

self.MAP[record.levelno]("%s: %s" % (record.name, record.msg))

to have access to parameters in logging calls.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.