Skip to content Skip to sidebar Skip to footer

How To Override Python Builtins With An Import Statement?

I want to log to a text file whatever is printed to sys.stdout. While I understand smarter people can come up with more elegant and Pythonic solutions, here is my solution class lo

Solution 1:

A similar solution, or logging stuff to a file, which also printed to std.out, is given in the logging cookbook. Here is how you can simply log stuff to a file called 'spam.log' and also print certain stuff to std.out:

import logging

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

In this example all messages go to the file, only higher levels go to console.

Solution 2:

Instead of placing your code inside the class, put it at the module level. This way it will be executed the first time the module is imported:

# logging.pyprint = my_print

Post a Comment for "How To Override Python Builtins With An Import Statement?"