mikip
mikip

Reputation: 1717

Capturing/Return the output message of python logging

Is there a way of obtaining/returning the message from a call to logging.debug()?

Thanks

Upvotes: 3

Views: 6108

Answers (3)

ncoghlan
ncoghlan

Reputation: 41486

Yes, providing a mechanism to easily capture and redirect event details without requiring any modification to the code emitting the events is the entire purpose of the logging module.

All you need to do is include an appropriate call to logging.basicConfig() as your application starts up and you can send logged events wherever you wish.

The simplest is to just log to stdout:

import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

For more advanced options, I suggest checking out the logging tutorial in the official documentation.

If you want programmatic access to the formatted message at the point of making the call... then the logging module is the wrong tool for the job. It is designed for emitting events, not for use as an alternative to calling str.format directly.

For the case you describe in your comment, you may want to consider a hierarchical logging setup along the following lines:

>>> import logging
>>> import sys
>>> logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
>>> master = logging.getLogger("master")
>>> child1 = logging.getLogger("master.child1")
>>> child2 = logging.getLogger("master.child2")
>>> child1.debug("Event from child 1")
DEBUG:master.child1:Event from child 1
>>> child2.debug("Event from child 2")
DEBUG:master.child2:Event from child 2

In this setup, note that I only configured a handler at the root level of the hierarchy (as part of the basicConfig() call). logging understands the "parent.child" notation in logger names, so it will pass any events passed to the child loggers up to the master logger, which in turn passes them on to the root logger.

You can add additional logging handlers at the master and child levels as necessary in order to redirect the output wherever you wish.

Upvotes: 4

das_weezul
das_weezul

Reputation: 6142

Well, logging.debug usually writes to a file. you can read that file by using the open() function.

Upvotes: 0

khachik
khachik

Reputation: 28693

Maybe replace logging.debug at startup?

import logging
d = logging.debug
def myDebug(*args):
  print "I'm a spy", args
  d(*args)
logging.debug = myDebug

Upvotes: 0

Related Questions