How do I use Django's logger to log a traceback when I tell it to?

后端 未结 2 1684
夕颜
夕颜 2021-01-03 19:16
try:
    print blah
except KeyError:
    traceback.print_exc()

I used to debug like this. I\'d print to the console. Now, I want to log everything

相关标签:
2条回答
  • 2021-01-03 19:43

    You can use python's logging mechanism:

    import logging
    ...
    
    logger = logging.getLogger("blabla")
    ...
    
    try:
        print blah # You can use logger.debug("blah") instead of print
    except KeyError:
        logger.exception("An error occurred")
    

    This will print the stack trace and will work with apache.

    0 讨论(0)
  • 2021-01-03 19:45

    If you're running Django's trunk version (or 1.3 when it's released), there are a number of default logging configurations built in which are integrated with Python's standard logging module. For that, all you need to do is import logging, call logger = logging.getLogger(__name__) and then call logger.exception(msg) and you'll get both your message and a stack trace. Docs for Django's logging functionality and Python's logger.exception method would be handy references.

    If you don't want to use Python's logging module, you can also import sys and write to sys.stderr rather than using print. On the command line this goes to the screen, when running under Apache it'll go into your error logs.

    0 讨论(0)
提交回复
热议问题