Logging in the blender game engine

Often it’s useful to log data in a game, and sometimes, print statements just don’t cut it. You may want to save it, you may only want to display things that are important and so on.
It should come as no surprise that python comes with a library for logging.

There are two parts to this:

1) Configuring the logger
We want the logger to output to a file and to the console. So we can create a function like:


import logging
import bge

LOG_FILENAME = bge.logic.expandPath('//game.log')
PRINT_LOG_LEVEL = logging.DEBUG  # or logging.INFO, logging.WARN, logging.ERROR

def create_logger():
    '''Configures the logging logger to write to a file and
    print messages'''
    log_file_path = Common.get_from_root(LOG_FILENAME)
    if os.path.isfile(log_file_path):
        os.remove(log_file_path)
    logging.basicConfig(filename=log_file_path, level=logging.DEBUG)

    log_printer = logging.StreamHandler(sys.stdout)
    log_printer.setLevel(PRINT_LOG_LEVEL)
    log_printer.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
    LOG.addHandler(log_printer)

Run that once from somewhere, and it will set up the logger to write to a file (called ‘game.log’ in this case), and to print with configurable printing level, to the console.

2) Using the logger in another module/script
We now have to add something to the logger. What I do is:


import logging

LOG = logging.getLogger()

def some_function():
    ....
    other code
    ....
    if situation:
        LOG.info("This is useful information, such as filepaths, screen resolution etc.")
    if error:
        LOG.error("Things blew up")

For more information, see the python documentation on the logging module.

with this system + pip, could python run pip, install a python module with os specific dependencies, run the module(in this case pyTTSx)log those dependencies, and copy them into the blender\python\lib?

This is just logging: ie saving error messages and warning to a file somewhere.

I see no reason why (external to this module) you couldn’t use PIP, but I don’t see how it is related to this resource.

I was thinking of logging the files the installed module calls,
(because they are os specific)
win32com on windows machines etc, and it is linked to windows speech stuff*