开发者

Capturing/Return the output message of python logging

开发者 https://www.devze.com 2023-02-24 03:29 出处:网络
Is there a way of obtainin开发者_如何学Cg/returning the message from a call to logging.debug()?

Is there a way of obtainin开发者_如何学Cg/returning the message from a call to logging.debug()?

Thanks


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消