Capturing/Return the output message of python logging
Question: Is there a way of obtaining/returning the message from a call to
logging.debug()?

Thanks


Answer: 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()`](http://docs.python.org/library/logging#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](http://docs.python.org/howto/logging.html#logging-basic-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](http://docs.python.org/howto/logging.html#loggers)
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.

