Milano
Milano

Reputation: 18745

Print exception with stack trace to file

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))

Upvotes: 23

Views: 23792

Answers (2)

user459872
user459872

Reputation: 24974

Starting from python 3.11 You can also use TracebackException.print(*, file=None, chain=True) to print the exception information directly into the file.

TracebackException objects are created from actual exceptions to capture data for later printing in a lightweight fashion

import traceback

try:
    1 / 0
except Exception as e:
    with open("error.txt", "w") as f:
        traceback.TracebackException.from_exception(e).print(file=f)

This will produce the traceback like this.

Traceback (most recent call last):
  File "C:/..../playground.py", line 4, in <module>
    1 / 0
    ~~^~~
ZeroDivisionError: division by zero

Upvotes: 0

Horacio
Horacio

Reputation: 2965

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())

Upvotes: 37

Related Questions