How do I capture stdout from submodules to my main logger in Python

Viewed 13

I want log the output generated by loaded modules in my main program.

I have my logger in my main program configured like this:

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)

# output handler
handler = logging.FileHandler(os.path.join(
    file_path, 'logs/logfile.log'), 'a')
handler.setFormatter(logging.Formatter(
    "%(asctime)s : %(levelname)s : [%(filename)s:%(lineno)s - %(funcName)s()] : %(message)s",
    "%Y-%m-%d %H:%M:%S"))
log.addHandler(handler)

# streamhandler for stderr and/or stdout from the modules
stream_hander = logging.StreamHandler(sys.stdout)
stream_hander.setLevel(level=logging.INFO)
stream_hander.setFormatter(logging.Formatter(
    "%(asctime)s : %(levelname)s : [%(filename)s:%(lineno)s - %(funcName)s()] : %(message)s",
    "%Y-%m-%d %H:%M:%S"))
log.addHandler(stream_hander)
stream_hander = logging.StreamHandler(sys.stderr)
stream_hander.setLevel(level=logging.ERROR)
stream_hander.setFormatter(logging.Formatter(
    "%(asctime)s : %(levelname)s : [%(filename)s:%(lineno)s - %(funcName)s()] : %(message)s",
    "%Y-%m-%d %H:%M:%S"))
log.addHandler(stream_hander)

However in submodules I load a basiclogger is used and prints/logs to stdout. This does print in my terminal, however these lines aren't written to the logfile. How can I capture this so all everything is written to the logfile. I prefer to do this in Python and not pipe the output of the script to a file with 2>&1

0 Answers
Related