0

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

9 Comments

I think this is not what I want, since I dont get a hint were the bug really is. In my orignial code the error message in the console is to long, to see it entirely, so I think this is not what I am looking for.
@swot: The full traceback is logged to your logfile. My sample exception is rather short, what makes you think this is a truncated traceback?
Actually, if I have def somefunction(): print a I didnt get the full traceback in my log file. Any suggestions?
@swot: Where did you catch the exception? At the entry point of your program or inside somefunction()?
create logger </br> somefuntion() </br> try:somefunction </br> except Exception: </br> logger.exception("oops) This is the way I set it up. Does this help?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.