0

so i followed a game building tutorial for python that is using pygame, i added some functionalties to it and it crashes after reaching a certain stage. I don't know which line is the problem so i implemented logging after reading a few tutorials about it, but i can't get the log file to show which line was the problem, i googled and the only code that actually showed it had try and except do i need to implement both of them in the game to be able to get the specific line? i am not sure if that will be efficent to do in a game. is there any way of making the log file inlcude the lines in it? Thanks! also i am new to coding, just putting it out there.

#logging config
logging.basicConfig(filename="log.txt", level=logging.DEBUG,filemode="w",format="%(asctime)s:%(levelname)s:%(message)s",datefmt="%d/%m/%Y %I:%M:%S %p")

#Logging
logging.debug('Debug Information')
logging.info('info Information')
logging.warning('warning Information')
logging.error('error Information')
logging.critical('critical Information')
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Icen
  • 123
  • 8
  • Python already tells the line where the exception occured. Can you paste the error you get ? – Capie Jan 08 '21 at 09:27
  • Does this answer your question? [How to log source file name and line number in Python](https://stackoverflow.com/questions/533048/how-to-log-source-file-name-and-line-number-in-python) – azro Jan 08 '21 at 09:28

1 Answers1

0

A solution would be to override the python default error handler, in order to add a logging command:

import sys
import traceback

logging.basicConfig(
    filename="log.txt",
    level=logging.DEBUG,
    filemode="w",
    format="%(asctime)s:%(levelname)s:%(message)s",
    datefmt="%d/%m/%Y %I:%M:%S %p"
)

SYS_EXCEPT_HOOK = sys.excepthook


def _excepthook(typ, value, trace):
    """ override builtin excepthook """
    logging.error("{}\n{}\n{}".format(typ.__name__, value, ''.join(traceback.format_tb(trace))))
    SYS_EXCEPT_HOOK(typ, value, trace)

sys.excepthook = _excepthook

a = 1 / 0

This will log:

08/01/2021 10:37:38 AM:ERROR:ZeroDivisionError
division by zero
  File "/home/devone/dev/scripts/sugar2dolibarr/test.py", line 23, in <module>
    a = 1 / 0

UPDATE

Every exception thrown is handled by the sys.excepthook builtin method.

Here I've created a new method (_excepthook, but you can pick the name you want) that will process the exception instead.

But since we still want python to handle this exception after we logged it, I stored the initial excepthook in a variable (here: SYS_EXCEPT_HOOK but again, you pick the name), and we call it immediatly after having logged the error.

Then we replace the default sys.excepthook by the one we just make.

The only role of the traceback lib is to reconstruct the traceback of the exception, like the default error handler does.

olinox14
  • 6,177
  • 2
  • 22
  • 39