23

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))
Milano
  • 18,048
  • 37
  • 153
  • 353
  • possible duplicate of [How to print the full traceback without halting the program?](http://stackoverflow.com/questions/3702675/how-to-print-the-full-traceback-without-halting-the-program) – Karl Barker Jul 26 '15 at 12:23
  • 1
    I recommend that you take a look at the [built-in python logging modules](https://docs.python.org/2/howto/logging.html#logging-basic-tutorial). This is a well covered topic; There should be no need to reinvent the wheel here. – Lix Jul 26 '15 at 12:31

2 Answers2

37

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())
Horacio
  • 2,865
  • 1
  • 14
  • 24
0

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
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46