Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 428
Milano Avatar asked Jul 26 '15 12:07

Milano


People also ask

How do I print an entire stack trace in exception?

Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.

Should we print stack trace for exceptions?

The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java's throwable class which prints the throwable along with other details like the line number and class name where the exception occurred. printStackTrace() is very useful in diagnosing exceptions.


1 Answers

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())
like image 175
Horacio Avatar answered Sep 23 '22 00:09

Horacio