Search code examples
pythondjangologgingtraceback

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


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 instead of print, since Apache doesn't allow printing. So, how do I log this entire traceback?


Solution

  • 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.