Print exception with stack trace to file

Milano picture Milano · Jul 26, 2015 · Viewed 13.1k times · Source

I'm trying to put a simple log into my script. This log should tell me where is the error and as much as possible info needed to repair the script.

I've put print to file str(e) into each except but it provides a very few info to know what is going wrong.

How could I make it elaborated? For example the whole not catched exception text which I can see in the console?

try:
    #code
except Exception as e:
   print_to_file(log.txt,str(e))

Answer

Horacio picture Horacio · Jul 26, 2015

try this,

import traceback
try:
    1/0 
except Exception as e:
    with open('log.txt', 'a') as f:
        f.write(str(e))
        f.write(traceback.format_exc())

If you want a better solution should use Logger that manage timestamps, file size, and rotation for syou (doing a logger handler)

this is an example with logger, timestamp and rotation

import logging
from logging.handlers import RotatingFileHandler
import traceback

logger = logging.getLogger("Rotating Log")
logger.setLevel(logging.ERROR)
handler = RotatingFileHandler("log.txt", maxBytes=10000, backupCount=5)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
try:
    1/0 
except Exception as e:
    logger.error(str(e))
    logger.error(traceback.format_exc())