简体   繁体   中英

Configure logging in Python

I have a question on how to configure my python logger. Below you can see my current set up of the logger. ( http://docs.python.org/2/howto/logging-cookbook.html )

logger = logging.getLogger("someName")
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler("./log/log.out", "w")
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stderr)
ch.setLevel(logging.ERROR)

frm = logging.Formatter('%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s','H:%M:%S')
fh.setFormatter(frm)
ch.setFormatter(frm)
logger.addHandler(fh)
logger.addHandler(ch)

Is there a way to configure the logger in such a way that it also writes error messages like the one below:

print a
>>> NameError: global name 'a' is not defined

Thanks a lot for your help.

Wrap your code in a try: , except Exception: block and call logger.exception() :

try:
    print a
except Exception:
    logger.exception('Oops, something went wrong')

You could add a raise statement to that to re-raise the caught exception.

Demo:

>>> import logging
>>> logging.basicConfig()
>>> logger = logging.getLogger()
>>> def foo():
...     print a
... 
>>> def bar(i=0):
...     if i < 3:
...         bar(i + 1)
...     else:
...         foo()
... 
>>> def baz():
...     try:
...         bar()
...     except Exception:
...        logger.exception('Oops, something went wrong')
... 
>>> def spam(): baz()
... 
>>> spam()
ERROR:root:Oops, something went wrong
Traceback (most recent call last):
  File "<stdin>", line 3, in baz
  File "<stdin>", line 3, in bar
  File "<stdin>", line 3, in bar
  File "<stdin>", line 3, in bar
  File "<stdin>", line 5, in bar
  File "<stdin>", line 2, in foo
NameError: global name 'a' is not defined

The traceback was logged by the logging module, not by my interactive Python session.

The traceback leads from the try block to the exception; the spam() function is the above example is not included.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM